import { NextResponse } from 'next/server';
import * as XLSX from 'xlsx';
import { AuthError, requireAllPermissions } from '@/lib/auth/session';
import { trainingRecordImportTemplateHeaders } from '@/features/training-records/constants/import-training-records';

export async function GET() {
  try {
    await requireAllPermissions(['training_record:write_all', 'training_record:approve']);

    const workbook = XLSX.utils.book_new();
    const worksheet = XLSX.utils.aoa_to_sheet([
      [...trainingRecordImportTemplateHeaders],
      [
        'EMP-001',
        'React Basic',
        '2026-01-15',
        'INTERNAL_TRAINING',
        'onsite',
        6,
        'K',
        'HRD Academy',
        'imported from legacy record'
      ],
      [
        'EMP-002',
        'Next.js',
        '2026-02-20',
        'ONLINE_COURSE',
        'online',
        8,
        'S',
        'Open Learning',
        ''
      ]
    ]);

    worksheet['!cols'] = trainingRecordImportTemplateHeaders.map(() => ({ wch: 20 }));

    XLSX.utils.book_append_sheet(workbook, worksheet, 'TrainingRecords');
    const buffer = XLSX.write(workbook, { type: 'buffer', bookType: 'xlsx' });

    return new NextResponse(buffer, {
      status: 200,
      headers: {
        'Content-Type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
        'Content-Disposition': 'attachment; filename="training-record-import-template.xlsx"'
      }
    });
  } catch (error) {
    if (error instanceof AuthError) {
      return NextResponse.json({ message: error.message }, { status: error.status });
    }

    return NextResponse.json({ message: 'ไม่สามารถสร้าง Template นำเข้าได้' }, { status: 500 });
  }
}
