import { NextRequest, NextResponse } from 'next/server';
import { AuthError } from '@/lib/auth/session';
import {
  createExcelBuffer,
  createPdfBuffer,
  getReportsAccess,
  getReportsDataset,
  parseReportFilters
} from '@/features/reports/server/report-data';

const supportedReports = new Set([
  'employeeTranscript',
  'trainingMatrix',
  'departmentSummary',
  'annualTrainingSummary'
] as const);

const supportedFormats = new Set(['xlsx', 'pdf'] as const);

type ExportableReport =
  | 'employeeTranscript'
  | 'trainingMatrix'
  | 'departmentSummary'
  | 'annualTrainingSummary';

type ExportFormat = 'xlsx' | 'pdf';

export async function GET(request: NextRequest) {
  try {
    const report = request.nextUrl.searchParams.get('report');
    const format = request.nextUrl.searchParams.get('format');

    if (!report || !supportedReports.has(report as ExportableReport)) {
      return NextResponse.json({ message: 'Unsupported report type' }, { status: 400 });
    }

    if (!format || !supportedFormats.has(format as ExportFormat)) {
      return NextResponse.json({ message: 'Unsupported export format' }, { status: 400 });
    }

    const filters = parseReportFilters({
      year: request.nextUrl.searchParams.get('year') ?? undefined,
      company: request.nextUrl.searchParams.get('company') ?? undefined,
      departmentId: request.nextUrl.searchParams.get('departmentId') ?? undefined
    });

    const access = await getReportsAccess();

    if (!access.canView) {
      return NextResponse.json({ message: 'Forbidden' }, { status: 403 });
    }

    if (!access.canViewAll && report !== 'employeeTranscript') {
      return NextResponse.json({ message: 'Forbidden' }, { status: 403 });
    }

    const { role: _role, ...dataset } = await getReportsDataset(filters, access);
    const today = new Date().toISOString().slice(0, 10);

    if (format === 'xlsx') {
      const buffer = createExcelBuffer(report as ExportableReport, dataset);

      return new NextResponse(buffer, {
        status: 200,
        headers: {
          'Content-Type':
            'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
          'Content-Disposition': `attachment; filename="${report}-${today}.xlsx"`
        }
      });
    }

    const buffer = await createPdfBuffer(report as ExportableReport, dataset);

    return new NextResponse(buffer, {
      status: 200,
      headers: {
        'Content-Type': 'application/pdf',
        'Content-Disposition': `attachment; filename="${report}-${today}.pdf"`
      }
    });
  } catch (error) {
    if (error instanceof AuthError) {
      return NextResponse.json({ message: error.message }, { status: error.status });
    }

    console.error('Failed to export report', error);
    return NextResponse.json({ message: 'Failed to export report' }, { status: 500 });
  }
}
