import type { RequestHandler } from './$types';
import { getDb } from '$lib/server/db';
import { sha256Hex } from '$lib/server/crypto';
import { validateIcsToken, buildIcsFeed, icsDateRange } from '$lib/server/ics-helpers';

export const GET: RequestHandler = async ({ params, request }) => {
  const db = await getDb();

  const res = await validateIcsToken(db, params.token || '', 'group');
  if (res instanceof Response) return res;
  const { row } = res;
  if (!row.group_id) return new Response('Not Found', { status: 404 });

  // Validar estado del grupo
  const gRow = db
    .prepare(`SELECT COALESCE(active,1) as active, COALESCE(archived,0) as archived, COALESCE(is_community,0) as is_community FROM groups WHERE id = ?`)
    .get(row.group_id) as any;
  if (!gRow || Number(gRow.active || 0) !== 1 || Number(gRow.archived || 0) === 1 || Number(gRow.is_community || 0) === 1) {
    return new Response('Gone', { status: 410 });
  }

  const tokenHash = await sha256Hex(params.token || '');
  const { startYmd, endYmd } = icsDateRange();

  const tasks = db
    .prepare(
      `SELECT t.id, t.description, t.due_date, g.name AS group_name
       FROM tasks t
       LEFT JOIN groups g ON g.id = t.group_id
       WHERE t.group_id = ?
         AND COALESCE(t.completed, 0) = 0
         AND t.due_date IS NOT NULL
         AND t.due_date >= ? AND t.due_date <= ?
         AND NOT EXISTS (SELECT 1 FROM task_assignments a WHERE a.task_id = t.id)
       ORDER BY t.due_date ASC, t.id ASC`
    )
    .all(row.group_id, startYmd, endYmd) as any[];

  return buildIcsFeed(db, tokenHash, row, request, 'Wtask.org Tareas – Grupo', tasks);
};
