import { NextRequest, NextResponse } from 'next/server';
import { query, getConfig } from '@/lib/db';
import { createCheckout } from '@/lib/lemonsqueezy';
import { Session } from '@/lib/types';

export async function POST(request: NextRequest) {
  try {
    const { session_id, email } = await request.json();

    if (!session_id) {
      return NextResponse.json({ error: 'Session ID required' }, { status: 400 });
    }

    // Look up session to get the tool
    const sessions = await query<Session>(
      'SELECT * FROM sessions WHERE id = $1 LIMIT 1',
      [session_id]
    );
    const session = sessions[0];
    if (!session) {
      return NextResponse.json({ error: 'Session not found' }, { status: 404 });
    }

    // Get per-tool variant ID from admin config
    const variantId = await getConfig(`variant_${session.tool}`);
    if (!variantId) {
      return NextResponse.json(
        { error: `Payment not configured for tool: ${session.tool}` },
        { status: 500 }
      );
    }

    const checkoutUrl = await createCheckout(
      variantId,
      session_id,
      email || session.email || undefined
    );

    return NextResponse.json({ checkout_url: checkoutUrl });
  } catch (error) {
    console.error('Create checkout error:', error);
    return NextResponse.json({ error: 'Failed to create checkout' }, { status: 500 });
  }
}
