import type { RequestHandler } from './$types';
import { loadTaskAndCheckGroup } from '$lib/server/task-helpers';

export const POST: RequestHandler = async (event) => {
  const ctx = await loadTaskAndCheckGroup(event);
  if (ctx instanceof Response) return ctx;
  const { db, task, userId } = ctx;

  const groupId: string | null = task.group_id ? String(task.group_id) : null;

  // Bloqueo de tareas personales: si es la última asignación del propio usuario, denegar
  const stats = db
    .prepare(`
      SELECT COUNT(*) AS cnt,
             SUM(CASE WHEN user_id = ? THEN 1 ELSE 0 END) AS mine
      FROM task_assignments
      WHERE task_id = ?
    `)
    .get(userId, task.id) as any;
  const cnt = Number(stats?.cnt || 0);
  const mine = Number(stats?.mine || 0) > 0;

  if (!groupId && cnt === 1 && mine) {
    return new Response('No puedes soltar una tarea personal. Márcala como completada para eliminarla', {
      status: 409,
      headers: { 'content-type': 'text/plain; charset=utf-8', 'cache-control': 'no-store' }
    });
  }

  // Eliminar asignación (idempotente)
  const delRes = db
    .prepare(`DELETE FROM task_assignments WHERE task_id = ? AND user_id = ?`)
    .run(task.id, userId) as any;

  const cntRow = db
    .prepare(`SELECT COUNT(*) AS cnt FROM task_assignments WHERE task_id = ?`)
    .get(task.id) as any;
  const remaining = Number(cntRow?.cnt || 0);

  const status = Number(delRes?.changes || 0) > 0 ? 'unassigned' : 'not_assigned';

  const body = {
    status,
    now_unassigned: remaining === 0,
    task: {
      id: Number(task.id),
      description: String(task.description || ''),
      due_date: task.due_date ? String(task.due_date) : null,
      display_code: task.display_code != null ? Number(task.display_code) : null
    }
  };

  return new Response(JSON.stringify(body), {
    status: 200,
    headers: { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' }
  });
};
