/**
 * ${VOCAB.factory} - Projects API
 * GET /api/dark-factory/projects - List all projects
 * POST /api/dark-factory/projects - Create a new project
 */

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';

// Helper to generate slug from name
function generateSlug(name: string): string {
  return name
    .toLowerCase()
    .replace(/[^a-z0-9]+/g, '-')
    .replace(/^-|-$/g, '')
    .substring(0, 50);
}

export async function GET(request: NextRequest) {
  const auth = await requireDFAuth();
  if (!auth.authorized) return auth.response;

  try {
    const searchParams = request.nextUrl.searchParams;
    const slug = searchParams.get('slug');
    const status = searchParams.get('status'); // active, archived, all
    const includeArchived = searchParams.get('includeArchived') === 'true';

    // If slug is provided, fetch single project with artifacts
    if (slug) {
      const project = await prisma.darkFactoryProject.findFirst({
        where: { slug },
      });

      if (!project) {
        return NextResponse.json({ project: null, artifacts: [] });
      }

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

      // Get artifacts from the latest task
      let artifacts: any[] = [];
      if (latestRequest?.task) {
        artifacts = await prisma.generatedArtifact.findMany({
          where: { taskId: latestRequest.task.id },
          select: {
            id: true,
            path: true,
            type: true,
            content: true,
            deployed: true,
          },
        });
      }

      return NextResponse.json({
        project: {
          id: project.id,
          name: project.name,
          slug: project.slug,
          description: project.description,
        },
        artifacts: artifacts.map(a => ({
          id: a.id,
          fileName: a.path.split('/').pop() || a.path,
          filePath: a.path,
          artifactType: a.type,
          code: a.content,
          status: a.deployed ? 'deployed' : 'generated',
        })),
        deployedAt: latestRequest?.task?.completedAt,
      });
    }

    // List all projects
    const where: Record<string, unknown> = {};
    
    if (status && status !== 'all') {
      where.status = status;
    } else if (!includeArchived) {
      where.status = { not: 'archived' };
    }

    const projects = await prisma.darkFactoryProject.findMany({
      where,
      orderBy: [
        { status: 'asc' }, // active first
        { lastActivityAt: 'desc' },
      ],
      include: {
        _count: {
          select: { requests: true },
        },
      },
    });

    return NextResponse.json({
      projects: projects.map((p: any) => ({
        ...p,
        requestCount: p._count.requests,
      })),
    });
  } catch (error) {
    console.error('Error fetching projects:', error);
    return NextResponse.json(
      { error: 'Failed to fetch projects' },
      { status: 500 }
    );
  }
}

export async function POST(request: NextRequest) {
  const auth = await requireDFAuth();
  if (!auth.authorized) return auth.response;

  try {
    const body = await request.json();
    const { name, description, businessDomain, tags, color } = body;

    if (!name || typeof name !== 'string' || name.trim().length === 0) {
      return NextResponse.json(
        { error: 'Project name is required' },
        { status: 400 }
      );
    }

    // Generate slug and ensure uniqueness
    let slug = generateSlug(name.trim());
    let suffix = 0;
    let uniqueSlug = slug;

    while (true) {
      const existing = await prisma.darkFactoryProject.findUnique({
        where: { slug: uniqueSlug },
      });
      if (!existing) break;
      suffix++;
      uniqueSlug = `${slug}-${suffix}`;
    }

    const project = await prisma.darkFactoryProject.create({
      data: {
        name: name.trim(),
        slug: uniqueSlug,
        description: description?.trim() || null,
        businessDomain: businessDomain?.trim() || null,
        tags: tags || [],
        color: color || '#0EA5E9',
        entities: [],
        taskCount: 0,
        artifactCount: 0,
      },
    });

    // Log event
    await prisma.factoryEvent.create({
      data: {
        type: 'project_created',
        payload: { projectId: project.id, name: project.name },
      },
    });

    return NextResponse.json({ project }, { status: 201 });
  } catch (error) {
    console.error('Error creating project:', error);
    return NextResponse.json(
      { error: 'Failed to create project' },
      { status: 500 }
    );
  }
}
