import type { RequestHandler } from './$types';
import { loadTaskAndGating, formatTask, respondTask } from '$lib/server/task-helpers';
import { UNCOMPLETE_WINDOW_MIN } from '$lib/server/env';
import { toIsoSqlUTC } from '$lib/server/datetime';

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

  // Idempotencia: ya está sin completar
  if (Number(task.completed) === 0) {
    return respondTask('already', {
      ...formatTask(task),
      completed: 0,
      completed_at: null
    });
  }

  // Validar ventana: completed_at dentro de UNCOMPLETE_WINDOW_MIN
  const taskId = task.id;
  if (!task.completed_at) {
    return new Response('Forbidden', { status: 403 });
  }
  const cutoff = toIsoSqlUTC(new Date(Date.now() - UNCOMPLETE_WINDOW_MIN * 60 * 1000));
  if (String(task.completed_at) < String(cutoff)) {
    return new Response('Forbidden', { status: 403 });
  }

  // Deshacer completar (no tocamos completed_by)
  db.prepare(`
    UPDATE tasks
    SET completed = 0,
        completed_at = NULL
    WHERE id = ?
  `).run(taskId);

  const updated = db.prepare(`
    SELECT id, description, due_date, display_code, COALESCE(completed, 0) AS completed, completed_at
    FROM tasks
    WHERE id = ?
  `).get(taskId) as any;

  return respondTask('updated', formatTask(updated));
};
