import { NextRequest, NextResponse } from 'next/server';
import { query } from '@/lib/db';
import { generate } from '@/lib/ai/client';
import { prompts } from '@/lib/ai/prompts';
import { ToolName, Session } from '@/lib/types';

export async function POST(
  request: NextRequest,
  { params }: { params: { tool: string } }
) {
  try {
    const tool = params.tool as ToolName;
    const { session_id } = await request.json();

    const [session] = await query<Session>(
      'SELECT * FROM sessions WHERE id = $1',
      [session_id]
    );
    if (!session) {
      return NextResponse.json({ error: 'Session not found' }, { status: 404 });
    }
    if (!session.is_paid) {
      return NextResponse.json({ error: 'Payment required' }, { status: 402 });
    }
    if (!session.output) {
      return NextResponse.json({ error: 'No output to validate' }, { status: 400 });
    }

    const toolPrompts = prompts[tool];
    const systemPrompt = 'You are a senior M&E and grant review specialist.';
    const userPrompt = toolPrompts.validate(session.output);

    const result = await generate(systemPrompt, userPrompt);

    await query(
      `INSERT INTO usage (session_id, tool, action, tokens_used) VALUES ($1, $2, $3, $4)`,
      [session_id, tool, 'validate', result.tokens]
    );

    return NextResponse.json({ validation: result.text });
  } catch (error) {
    console.error('Validate error:', error);
    return NextResponse.json({ error: 'Failed to validate' }, { status: 500 });
  }
}
