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

export async function GET() {
  try {
    const tasks = await sql`SELECT * FROM production_tasks ORDER BY name ASC`;
    return Response.json(tasks);
  } catch (error) {
    console.error(error);
    return Response.json({ error: 'Failed to fetch tasks' }, { status: 500 });
  }
}

export async function POST(request: Request) {
  try {
    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`
      INSERT INTO production_tasks (name, insole_types)
      VALUES (${name}, ${types})
      RETURNING *
    `;
    return Response.json(task);
  } catch (error) {
    console.error(error);
    return Response.json({ error: 'Failed to create task' }, { status: 500 });
  }
}
