import type { RequestHandler } from './$types';
import { getDb } from '$lib/server/db';

export const POST: RequestHandler = async (event) => {
  const userId = event.locals.userId ?? null;
  if (!userId) {
    return new Response('Unauthorized', { status: 401 });
  }

  const idStr = event.params.id || '';
  const taskId = parseInt(idStr, 10);
  if (!Number.isFinite(taskId) || taskId <= 0) {
    return new Response('Bad Request', { status: 400 });
  }

  const db = await getDb();

  // Cargar tarea y validar abierta
  const task = db
    .prepare(
      `SELECT id, description, due_date, group_id, COALESCE(completed, 0) AS completed, completed_at, display_code
       FROM tasks
       WHERE id = ?`
    )
    .get(taskId) as any;

  if (!task) {
    return new Response(JSON.stringify({ status: 'not_found' }), {
      status: 404,
      headers: { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' }
    });
  }
  if (Number(task.completed) !== 0 || task.completed_at) {
    return new Response(JSON.stringify({ status: 'completed' }), {
      status: 400,
      headers: { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' }
    });
  }

  // Gating: grupo permitido + usuario miembro activo (si tiene group_id)
  const groupId: string | null = task.group_id ? String(task.group_id) : null;
  if (groupId) {
    const allowed = db
      .prepare(`SELECT 1 FROM allowed_groups WHERE group_id = ? AND status = 'allowed' LIMIT 1`)
      .get(groupId);
    const active = db
      .prepare(
        `SELECT 1 FROM group_members WHERE group_id = ? AND user_id = ? AND is_active = 1 LIMIT 1`
      )
      .get(groupId, userId);

    if (!allowed || !active) {
      return new Response('Forbidden', { status: 403 });
    }
  }

  // Asegurar existencia del usuario (best-effort)
  try {
    db.transaction(() => {
      db.prepare(
        `INSERT INTO users (id, first_seen, last_seen)
         VALUES (?, strftime('%Y-%m-%d %H:%M:%f','now'), strftime('%Y-%m-%d %H:%M:%f','now'))
         ON CONFLICT(id) DO NOTHING`
      ).run(userId);
      db.prepare(
        `UPDATE users SET last_seen = strftime('%Y-%m-%d %H:%M:%f','now') WHERE id = ?`
      ).run(userId);
    })();
  } catch {}

  // Reclamar (idempotente)
  const res = db
    .prepare(
      `INSERT OR IGNORE INTO task_assignments (task_id, user_id, assigned_by)
       VALUES (?, ?, ?)`
    )
    .run(taskId, userId, userId) as any;

  const status = Number(res?.changes || 0) > 0 ? 'claimed' : 'already';

  const body = {
    status,
    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' }
  });
};
