/**
 * ${VOCAB.factory} - Single Project API
 * GET /api/dark-factory/projects/[id] - Get project details
 * PUT /api/dark-factory/projects/[id] - Update project
 * DELETE /api/dark-factory/projects/[id] - Delete 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';

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

  try {
    const { id } = await params;

    const project = await prisma.darkFactoryProject.findUnique({
      where: { id },
      include: {
        requests: {
          orderBy: { createdAt: 'desc' },
          take: 10,
          include: {
            task: {
              include: {
                artifacts: true,
              },
            },
          },
        },
        _count: {
          select: { requests: true },
        },
      },
    });

    if (!project) {
      return NextResponse.json(
        { error: 'Project not found' },
        { status: 404 }
      );
    }

    return NextResponse.json({
      project: {
        ...project,
        requestCount: project._count.requests,
      },
    });
  } catch (error) {
    console.error('Error fetching project:', error);
    return NextResponse.json(
      { error: 'Failed to fetch project' },
      { status: 500 }
    );
  }
}

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

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

    const existing = await prisma.darkFactoryProject.findUnique({
      where: { id },
    });

    if (!existing) {
      return NextResponse.json(
        { error: 'Project not found' },
        { status: 404 }
      );
    }

    const updateData: Record<string, unknown> = {};
    if (name !== undefined) updateData.name = name.trim();
    if (description !== undefined) updateData.description = description?.trim() || null;
    if (businessDomain !== undefined) updateData.businessDomain = businessDomain?.trim() || null;
    if (status !== undefined) updateData.status = status;
    if (tags !== undefined) updateData.tags = tags;
    if (color !== undefined) updateData.color = color;

    const project = await prisma.darkFactoryProject.update({
      where: { id },
      data: updateData,
    });

    // Log status change
    if (status && status !== existing.status) {
      await prisma.factoryEvent.create({
        data: {
          type: 'project_status_changed',
          payload: {
            projectId: project.id,
            oldStatus: existing.status,
            newStatus: status,
          },
        },
      });
    }

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

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

  try {
    const { id } = await params;

    const project = await prisma.darkFactoryProject.findUnique({
      where: { id },
      include: {
        _count: { select: { requests: true } },
      },
    });

    if (!project) {
      return NextResponse.json(
        { error: 'Project not found' },
        { status: 404 }
      );
    }

    // If project has tasks, archive instead of delete
    if (project._count.requests > 0) {
      await prisma.darkFactoryProject.update({
        where: { id },
        data: { status: 'archived' },
      });

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

      return NextResponse.json({
        message: 'Project archived (has existing tasks)',
        archived: true,
      });
    }

    // Otherwise, delete
    await prisma.darkFactoryProject.delete({
      where: { id },
    });

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

    return NextResponse.json({ message: 'Project deleted', deleted: true });
  } catch (error) {
    console.error('Error deleting project:', error);
    return NextResponse.json(
      { error: 'Failed to delete project' },
      { status: 500 }
    );
  }
}
