/**
 * ${VOCAB.factory} - Single Task API
 * GET /api/dark-factory/tasks/[taskId]
 * DELETE /api/dark-factory/tasks/[taskId]
 */

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<{ taskId: string }> }
) {
  const auth = await requireDFAuth();
  if (!auth.authorized) return auth.response;

  try {
    const { taskId } = await params;

    const task = await prisma.generationTask.findUnique({
      where: { id: taskId },
      include: {
        request: {
          include: {
            project: true,
          },
        },
        artifacts: true,
        validations: true,
        deployments: {
          select: {
            id: true,
            environment: true,
            status: true,
            deployedAt: true,
            liveUrl: true,
            appSlug: true,
          },
        },
      },
    });

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

    // Transform artifacts to match expected interface
    const transformedTask = {
      ...task,
      artifacts: task.artifacts.map((artifact: any) => ({
        id: artifact.id,
        type: artifact.type,
        name: artifact.path.split('/').pop() || artifact.path, // Extract filename from path
        path: artifact.path,
        code: artifact.content || '', // Map content to code
        dependencies: [], // No dependencies stored in DB
        description: null, // No description stored in DB
        generatedAt: artifact.createdAt?.toISOString() || new Date().toISOString(),
      })),
    };

    return NextResponse.json({ data: transformedTask });
  } catch (error) {
    console.error('Error fetching task:', error);
    return NextResponse.json(
      { error: 'Failed to fetch task' },
      { status: 500 }
    );
  }
}

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

  try {
    const { taskId } = await params;

    // First check if task exists
    const task = await prisma.generationTask.findUnique({
      where: { id: taskId },
      include: { request: true },
    });

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

    // Delete in correct order due to foreign key constraints
    // 1. Delete validations
    await prisma.validationResult.deleteMany({
      where: { taskId },
    });

    // 2. Delete deployments
    await prisma.deployment.deleteMany({
      where: { taskId },
    });

    // 3. Delete artifacts
    await prisma.generatedArtifact.deleteMany({
      where: { taskId },
    });

    // 4. Delete the task itself
    await prisma.generationTask.delete({
      where: { id: taskId },
    });

    // 5. Delete the generation request
    await prisma.generationRequest.delete({
      where: { id: task.requestId },
    });

    // 6. Update project stats if task was associated with a project
    if (task.request?.projectId) {
      await prisma.darkFactoryProject.update({
        where: { id: task.request.projectId },
        data: {
          taskCount: { decrement: 1 },
          lastActivityAt: new Date(),
        },
      });
    }

    return NextResponse.json({
      success: true,
      message: 'Task and associated data deleted successfully',
    });
  } catch (error) {
    console.error('Error deleting task:', error);
    return NextResponse.json(
      { error: 'Failed to delete task' },
      { status: 500 }
    );
  }
}
