import { NextRequest, NextResponse } from 'next/server';
import {
  getAuditActionLabel,
  getAuditModuleLabel
} from '@/features/audit-logs/constants/audit-log-options';
import { auditLogFilterSchema } from '@/features/audit-logs/schemas/audit-log';
import { listAuditLogsForOrganization } from '@/features/audit-logs/server/audit-log-data';
import { AuthError, requireIT } from '@/lib/auth/session';

function escapeCsvCell(value: string) {
  return `"${value.replaceAll('"', '""')}"`;
}

export async function GET(request: NextRequest) {
  try {
    const { organization } = await requireIT();
    const filters = auditLogFilterSchema.parse({
      page: 1,
      limit: 1000,
      search: request.nextUrl.searchParams.get('search') ?? undefined,
      user: request.nextUrl.searchParams.get('user') ?? undefined,
      module: request.nextUrl.searchParams.get('module') ?? undefined,
      action: request.nextUrl.searchParams.get('action') ?? undefined,
      dateFrom: request.nextUrl.searchParams.get('dateFrom') ?? undefined,
      dateTo: request.nextUrl.searchParams.get('dateTo') ?? undefined
    });

    const result = await listAuditLogsForOrganization({
      organizationId: organization.id,
      filters
    });

    const rows = [
      ['วันที่', 'ผู้ใช้งาน', 'อีเมล', 'โมดูล', 'รายการ', 'รายละเอียด', 'IP'],
      ...result.auditLogs.map((log) => [
        new Intl.DateTimeFormat('th-TH', {
          dateStyle: 'medium',
          timeStyle: 'short'
        }).format(new Date(log.created_at)),
        log.user_name ?? 'ระบบ',
        log.user_email ?? '',
        getAuditModuleLabel(log.module_name),
        getAuditActionLabel(log.action),
        log.details,
        log.ip_address ?? ''
      ])
    ];

    const csv = rows.map((row) => row.map((cell) => escapeCsvCell(String(cell))).join(',')).join('\n');

    return new NextResponse(`\uFEFF${csv}`, {
      headers: {
        'Content-Type': 'text/csv; charset=utf-8',
        'Content-Disposition': 'attachment; filename="audit-logs.csv"'
      }
    });
  } catch (error) {
    if (error instanceof AuthError) {
      return NextResponse.json({ message: error.message }, { status: error.status });
    }

    return NextResponse.json({ message: 'ไม่สามารถส่งออกประวัติการใช้งานได้' }, { status: 500 });
  }
}
