/**
 * ${VOCAB.factory} - List Artifacts API
 * GET /api/dark-factory/artifacts
 * 
 * Returns a list of generated artifacts with optional filtering
 */

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

  try {
    const { searchParams } = new URL(request.url);
    const type = searchParams.get('type');
    const taskId = searchParams.get('taskId');
    const limit = parseInt(searchParams.get('limit') || '50');
    const offset = parseInt(searchParams.get('offset') || '0');

    const where: any = {};
    
    if (type) {
      where.type = type;
    }
    
    if (taskId) {
      where.taskId = taskId;
    }

    const [artifacts, total] = await Promise.all([
      prisma.generatedArtifact.findMany({
        where,
        orderBy: { createdAt: 'desc' },
        take: limit,
        skip: offset,
        include: {
          task: {
            select: {
              id: true,
              status: true,
              request: {
                select: {
                  prompt: true,
                  project: {
                    select: {
                      id: true,
                      name: true,
                      slug: true,
                    },
                  },
                },
              },
            },
          },
        },
      }),
      prisma.generatedArtifact.count({ where }),
    ]);

    return NextResponse.json({
      artifacts: artifacts.map((a: any) => {
        const prompt = a.task.request?.prompt || '';
        return {
          id: a.id,
          taskId: a.taskId,
          type: a.type,
          path: a.path,
          contentPreview: a.content.substring(0, 200) + (a.content.length > 200 ? '...' : ''),
          contentLength: a.content.length,
          checksum: a.checksum,
          version: a.version,
          deployed: a.deployed,
          createdAt: a.createdAt,
          task: {
            id: a.task.id,
            status: a.task.status,
            prompt: prompt.substring(0, 100) + (prompt.length > 100 ? '...' : ''),
            project: a.task.request?.project || null,
          },
        };
      }),
      total,
      limit,
      offset,
    });

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