/**
 * ${VOCAB.factory} - Archive/Unarchive Project
 * POST /api/dark-factory/projects/[id]/archive - Toggle archive status
 */

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 POST(
  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().catch(() => ({}));
    const { archive } = body; // true to archive, false to unarchive

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

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

    const shouldArchive = archive !== undefined ? archive : project.status !== 'archived';
    const newStatus = shouldArchive ? 'archived' : 'active';

    const updated = await prisma.darkFactoryProject.update({
      where: { id },
      data: { status: newStatus },
    });

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

    return NextResponse.json({
      project: updated,
      message: shouldArchive ? 'Project archived' : 'Project restored',
    });
  } catch (error) {
    console.error('Error archiving project:', error);
    return NextResponse.json(
      { error: 'Failed to archive project' },
      { status: 500 }
    );
  }
}
