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

export async function PUT(request: Request, { params }: { params: Promise<{ id: string }> }) {
  try {
    const { id } = await params;
    const { name, insole_types } = await request.json();
    if (!name) return Response.json({ error: 'Name is required' }, { status: 400 });

    const types: string[] =
      Array.isArray(insole_types) && insole_types.length > 0
        ? insole_types
        : ['Kurk', 'Berk', '3D'];

    const [task] = await sql`
      UPDATE production_tasks
      SET name = ${name}, insole_types = ${types}
      WHERE id = ${id}
      RETURNING *
    `;
    if (!task) return Response.json({ error: 'Task not found' }, { status: 404 });
    return Response.json(task);
  } catch (error) {
    console.error(error);
    return Response.json({ error: 'Failed to update task' }, { status: 500 });
  }
}

export async function DELETE(_request: Request, { params }: { params: Promise<{ id: string }> }) {
  try {
    const { id } = await params;
    await sql`DELETE FROM time_logs WHERE task_id = ${id}`;
    await sql`DELETE FROM production_tasks WHERE id = ${id}`;
    return Response.json({ success: true });
  } catch (error) {
    console.error(error);
    return Response.json({ error: 'Failed to delete task' }, { status: 500 });
  }
}
