/**
 * ${VOCAB.factory} - Task Status API
 * GET /api/dark-factory/status/[taskId]
 * 
 * Returns the current status of a generation task
 * Accepts either a taskId or requestId
 */

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

interface RouteContext {
  params: Promise<{ taskId: string }>;
}

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

  try {
    const { taskId } = await context.params;

    if (!taskId) {
      return NextResponse.json(
        { error: 'Task ID is required' },
        { status: 400 }
      );
    }

    // First try to find task directly by ID
    let taskData = await prisma.generationTask.findUnique({
      where: { id: taskId },
      include: {
        artifacts: true,
      },
    });

    // If not found, try to find by requestId
    if (!taskData) {
      taskData = await prisma.generationTask.findFirst({
        where: { requestId: taskId },
        include: {
          artifacts: true,
        },
        orderBy: { createdAt: 'desc' },
      });
    }

    // If task found, return its status
    if (taskData) {
      return NextResponse.json({
        id: taskData.id,
        requestId: taskData.requestId,
        status: taskData.status,
        stages: taskData.stages || [],
        artifactCount: taskData.artifacts?.length || 0,
        artifacts: taskData.artifacts?.map((a: any) => ({
          id: a.id,
          type: a.type,
          path: a.path,
        })),
        startedAt: taskData.startedAt,
        completedAt: taskData.completedAt,
        error: taskData.error,
      });
    }

    // If no task found, check if request exists but task not yet created
    const requestData = await prisma.generationRequest.findUnique({
      where: { id: taskId },
    });

    if (requestData) {
      // Request exists but task not yet created - still processing
      return NextResponse.json({
        id: taskId,
        requestId: taskId,
        status: requestData.status || 'processing',
        stages: [],
        artifactCount: 0,
        artifacts: [],
        message: 'Generation in progress',
      });
    }

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

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