import sql from '@/app/api/utils/sql';

const quote = (value: string | number) => `"${String(value).replace(/"/g, '""')}"`;

export async function GET() {
  try {
    const logs = await sql`
      SELECT 
        tl.id,
        pt.name as task_name,
        tl.start_time,
        tl.end_time,
        tl.duration_seconds,
        tl.pair_count,
        tl.insole_type,
        tl.notes
      FROM time_logs tl
      JOIN production_tasks pt ON tl.task_id = pt.id
      ORDER BY tl.start_time ASC
    `;

    const headers = [
      'ID',
      'Task',
      'Insole Type',
      'No. of Insoles',
      'Date',
      'Total Duration',
      'Start Time',
      'End Time',
    ];

    const rows = logs.map((log) => {
      const start = new Date(log.start_time);
      const end = log.end_time ? new Date(log.end_time) : null;

      const dateStr = start.toLocaleDateString('nl-BE', {
        day: '2-digit',
        month: '2-digit',
        year: 'numeric',
      });
      const startTimeStr = start.toLocaleTimeString('nl-BE', {
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit',
      });
      const endTimeStr = end
        ? end.toLocaleTimeString('nl-BE', {
            hour: '2-digit',
            minute: '2-digit',
            second: '2-digit',
          })
        : '';

      const totalSeconds = log.duration_seconds || 0;
      const hours = Math.floor(totalSeconds / 3600);
      const minutes = Math.floor((totalSeconds % 3600) / 60);
      const seconds = totalSeconds % 60;
      const totalFormatted = `${String(hours).padStart(2, '0')}:${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}`;

      return [
        log.id,
        log.task_name,
        log.insole_type ?? 'Kurk',
        log.pair_count ?? 2,
        dateStr,
        totalFormatted,
        startTimeStr,
        endTimeStr,
      ].map(quote);
    });

    const csvContent = [headers.map(quote).join(','), ...rows.map((row) => row.join(','))].join(
      '\n'
    );

    return new Response(csvContent, {
      headers: {
        'Content-Type': 'text/csv; charset=utf-8',
        'Content-Disposition': 'attachment; filename="insole-production-report.csv"',
      },
    });
  } catch (error) {
    console.error(error);
    return Response.json({ error: 'Failed to export data' }, { status: 500 });
  }
}
