import { NextRequest, NextResponse } from 'next/server';
import { query, getConfig } 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, section, feedback } = await request.json();

    if (!session_id || !section || !feedback) {
      return NextResponse.json({ error: 'Missing required fields' }, { status: 400 });
    }

    // Check session is paid
    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 });
    }

    // Check improvement cap
    const maxImprovements = parseInt((await getConfig('max_improvements')) || '5');
    if (session.improvements_used >= maxImprovements) {
      return NextResponse.json({ error: 'Improvement limit reached' }, { status: 429 });
    }

    const toolPrompts = prompts[tool];
    const systemPrompt = 'You are a professional NGO grant writing assistant.';
    const userPrompt = toolPrompts.improve(section, feedback);

    const result = await generate(systemPrompt, userPrompt);

    // Update session
    await query(
      `UPDATE sessions SET improvements_used = improvements_used + 1, updated_at = NOW() WHERE id = $1`,
      [session_id]
    );

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

    return NextResponse.json({ improved: result.text });
  } catch (error) {
    console.error('Improve section error:', error);
    return NextResponse.json({ error: 'Failed to improve section' }, { status: 500 });
  }
}
