import { NextResponse } from 'next/server';
import * as XLSX from 'xlsx';
import {
  thaiImportEmployeeHeaders,
  thaiImportTemplateHeaders,
  thaiImportTrainingHeaders
} from '@/constants/thai-labels';
import { AuthError, requireHRD } from '@/lib/auth/session';

export async function GET() {
  try {
    await requireHRD();

    const workbook = XLSX.utils.book_new();
    const worksheet = XLSX.utils.aoa_to_sheet([
      [...thaiImportTemplateHeaders],
      [
        'EMP-001',
        'สมชาย ใจดี',
        'somchai@example.com',
        'บริษัทตัวอย่าง',
        'ฝ่ายผลิต',
        'ช่างเทคนิค',
        'ใช้งาน',
        'React Basic',
        'K',
        6,
        'INTERNAL_TRAINING',
        '2026-01-15'
      ],
      [
        'EMP-001',
        'สมชาย ใจดี',
        'somchai@example.com',
        'บริษัทตัวอย่าง',
        'ฝ่ายผลิต',
        'ช่างเทคนิค',
        'ใช้งาน',
        'Next.js',
        'S',
        8,
        'ONLINE_COURSE',
        '2026-02-20'
      ]
    ]);

    worksheet['!cols'] = [
      ...thaiImportEmployeeHeaders.map(() => ({ wch: 20 })),
      ...thaiImportTrainingHeaders.map(() => ({ wch: 22 }))
    ];

    XLSX.utils.book_append_sheet(workbook, worksheet, 'Employees');
    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="employee-import-template-th.xlsx"'
      }
    });
  } catch (error) {
    if (error instanceof AuthError) {
      return NextResponse.json({ message: error.message }, { status: error.status });
    }

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