/**
 * ${VOCAB.factory} - Feedback API
 * POST /api/dark-factory/feedback
 * 
 * Captures user feedback for deployed apps
 */

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

  try {
    const body = await request.json();
    const { appSlug, feedback, url, screenshot } = body;

    if (!appSlug || !feedback) {
      return NextResponse.json(
        { error: 'App slug and feedback are required' },
        { status: 400 }
      );
    }

    // Find the latest deployment for this app
    const deployment = await prisma.deployment.findFirst({
      where: { appSlug },
      orderBy: { createdAt: 'desc' },
      include: {
        task: {
          include: {
            request: true,
          },
        },
      },
    });

    // Create a feedback event
    const event = await prisma.factoryEvent.create({
      data: {
        type: 'user_feedback',
        taskId: deployment?.taskId,
        payload: {
          appSlug,
          feedback,
          url,
          screenshot,
          deploymentId: deployment?.id,
          projectId: deployment?.task?.request?.projectId,
          timestamp: new Date().toISOString(),
        },
      },
    });

    // TODO: In future, this feedback could trigger an AI agent to:
    // 1. Analyze the feedback
    // 2. Identify the issue in the generated code
    // 3. Generate a fix
    // 4. Create a new generation task for the fix

    return NextResponse.json({
      success: true,
      eventId: event.id,
      message: 'Feedback received. Our AI will analyze and fix the issue.',
    });

  } catch (error) {
    console.error('Feedback error:', error);
    return NextResponse.json(
      { error: 'Failed to submit feedback' },
      { status: 500 }
    );
  }
}

// GET - List feedback for a project/app
export async function GET(request: NextRequest) {
  const auth = await requireDFAuth();
  if (!auth.authorized) return auth.response;

  try {
    const { searchParams } = new URL(request.url);
    const appSlug = searchParams.get('appSlug');

    const feedbackEvents = await prisma.factoryEvent.findMany({
      where: {
        type: 'user_feedback',
      },
      orderBy: { timestamp: 'desc' },
      take: 50,
    });

    // Filter by appSlug if provided (JSON filtering in memory)
    const filtered = appSlug
      ? feedbackEvents.filter((e: any) => {
          const payload = e.payload as any;
          return payload?.appSlug === appSlug;
        })
      : feedbackEvents;

    return NextResponse.json({
      feedback: filtered.map((e: any) => ({
        id: e.id,
        ...((e.payload as any) || {}),
        timestamp: e.timestamp,
      })),
    });

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