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;

  // 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(task.id, 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' }
  });
};
