import { NextRequest, NextResponse } from 'next/server';
import { query } from '@/lib/db';
import { Session } from '@/lib/types';
import { generateDocx } from '@/lib/exports/docx';
import { generateExcel } from '@/lib/exports/excel';
import { generatePdf } from '@/lib/exports/pdf';

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

    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 export' }, { status: 400 });
    }

    switch (format) {
      case 'docx': {
        const buffer = await generateDocx(session.output, session.tool);
        return new NextResponse(new Uint8Array(buffer), {
          headers: {
            'Content-Type': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
            'Content-Disposition': `attachment; filename="${session.tool}-output.docx"`,
          },
        });
      }
      case 'excel': {
        const buffer = await generateExcel(session.output, session.tool);
        return new NextResponse(new Uint8Array(buffer), {
          headers: {
            'Content-Type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
            'Content-Disposition': `attachment; filename="${session.tool}-output.xlsx"`,
          },
        });
      }
      case 'pdf': {
        const buffer = await generatePdf(session.output, session.tool);
        return new NextResponse(new Uint8Array(buffer), {
          headers: {
            'Content-Type': 'application/pdf',
            'Content-Disposition': `attachment; filename="${session.tool}-output.pdf"`,
          },
        });
      }
      case 'copy': {
        return NextResponse.json({ text: session.output });
      }
      default:
        return NextResponse.json({ error: 'Invalid format' }, { status: 400 });
    }
  } catch (error) {
    console.error('Export error:', error);
    return NextResponse.json({ error: 'Failed to export' }, { status: 500 });
  }
}
