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

export async function GET() {
  try {
    const logs = await sql`
      SELECT 
        tl.id,
        pt.name AS task_name,
        tl.task_id,
        tl.start_time,
        tl.end_time,
        tl.duration_seconds,
        tl.pair_count,
        tl.insole_type,
        tl.notes,
        tl.created_at
      FROM time_logs tl
      JOIN production_tasks pt ON tl.task_id = pt.id
      ORDER BY tl.start_time DESC
    `;
    return Response.json(logs);
  } catch (error) {
    console.error(error);
    return Response.json({ error: 'Failed to fetch logs' }, { status: 500 });
  }
}

export async function POST(request: Request) {
  try {
    const { task_id, start_time, end_time, duration_seconds, pair_count, insole_type, notes } =
      await request.json();

    if (!task_id || !start_time || !end_time || duration_seconds === undefined) {
      return Response.json({ error: 'Missing required fields' }, { status: 400 });
    }

    const [log] = await sql`
      INSERT INTO time_logs (task_id, start_time, end_time, duration_seconds, pair_count, insole_type, notes)
      VALUES (${task_id}, ${start_time}, ${end_time}, ${duration_seconds}, ${pair_count ?? 2}, ${insole_type ?? 'Kurk'}, ${notes ?? null})
      RETURNING *
    `;
    return Response.json(log);
  } catch (error) {
    console.error(error);
    return Response.json({ error: 'Failed to save log' }, { status: 500 });
  }
}
