/**
 * ${VOCAB.factory} - App Lookup API
 * GET /api/dark-factory/apps/[slug]
 * 
 * Looks up deployed app by slug (checks both project slug and deployment appSlug)
 */

import { NextRequest, NextResponse } from 'next/server';
import { prisma } from '@/lib/db';
import { VOCAB } from '@/lib/white-label/constants';
import { requireDFAuth } from '@/lib/dark-factory/auth-guard';

export const dynamic = 'force-dynamic';

export async function GET(
  request: NextRequest,
  { params }: { params: Promise<{ slug: string }> }
) {
  const auth = await requireDFAuth();
  if (!auth.authorized) return auth.response;

  try {
    const { slug } = await params;

    // First, try to find a project with this slug
    const project = await prisma.darkFactoryProject.findFirst({
      where: { slug },
    });

    if (project) {
      // Find the most recent deployed task for this project
      const latestRequest = await prisma.generationRequest.findFirst({
        where: { 
          projectId: project.id,
          status: 'completed',
        },
        include: {
          task: {
            include: {
              artifacts: true,
              deployments: {
                where: { status: 'deployed' },
                orderBy: { deployedAt: 'desc' },
                take: 1,
              },
            },
          },
        },
        orderBy: { updatedAt: 'desc' },
      });

      return NextResponse.json({
        found: true,
        type: 'project',
        project: {
          id: project.id,
          name: project.name,
          slug: project.slug,
          description: project.description,
        },
        artifacts: latestRequest?.task?.artifacts || [],
        deployment: latestRequest?.task?.deployments?.[0] || null,
      });
    }

    // If no project, try to find a deployment with this appSlug
    const deployment = await prisma.deployment.findFirst({
      where: { 
        appSlug: slug,
        status: 'deployed',
      },
      include: {
        task: {
          include: {
            artifacts: true,
            request: {
              include: {
                project: true,
              },
            },
          },
        },
      },
      orderBy: { deployedAt: 'desc' },
    });

    if (deployment) {
      const taskRequest = deployment.task.request;
      return NextResponse.json({
        found: true,
        type: 'deployment',
        project: taskRequest?.project ? {
          id: taskRequest.project.id,
          name: taskRequest.project.name,
          slug: taskRequest.project.slug,
          description: taskRequest.project.description,
        } : {
          id: deployment.id,
          name: 'Generated App',
          slug: deployment.appSlug,
          description: taskRequest?.prompt || 'Auto-generated application',
        },
        artifacts: deployment.task.artifacts,
        deployment: {
          id: deployment.id,
          status: deployment.status,
          deployedAt: deployment.deployedAt,
          liveUrl: deployment.liveUrl,
          logs: deployment.logs,
        },
        prompt: taskRequest?.prompt,
      });
    }

    // Not found
    return NextResponse.json({
      found: false,
      error: 'App not found',
    });

  } catch (error) {
    console.error('Error fetching app:', error);
    return NextResponse.json(
      { found: false, error: 'Failed to fetch app' },
      { status: 500 }
    );
  }
}
