import type { RequestHandler } from './$types';
import { getDb } from '$lib/server/db';
import { sha256Hex } from '$lib/server/crypto';
import { icsHorizonMonths } from '$lib/server/env';
import { buildIcsCalendar, checkIcsRateLimit } from '$lib/server/ics';
import { toIsoSqlUTC, ymdUTC, addMonthsUTC } from '$lib/server/datetime';

export const GET: RequestHandler = async ({ params, request }) => {
  const db = await getDb();
  const token = params.token || '';
  if (!token) return new Response('Not Found', { status: 404 });

  const tokenHash = await sha256Hex(token);
  const row = db
    .prepare(
      `SELECT id, type, user_id, group_id, revoked_at
       FROM calendar_tokens
       WHERE token_hash = ?
       LIMIT 1`
    )
    .get(tokenHash) as any;

  if (!row) return new Response('Not Found', { status: 404 });
  if (row.revoked_at) return new Response('Gone', { status: 410 });
  if (String(row.type) !== 'aggregate') return new Response('Not Found', { status: 404 });

  const rl = checkIcsRateLimit(tokenHash);
  if (!rl.ok) {
    return new Response('Too Many Requests', { status: 429, headers: { 'Retry-After': String(rl.retryAfterSec || 60) } });
  }

  const today = new Date();
  const startYmd = ymdUTC(today);
  const endYmd = ymdUTC(addMonthsUTC(today, icsHorizonMonths));

  // Sin responsable en todos los grupos allowed donde el usuario esté activo
  const tasks = db
    .prepare(
      `SELECT t.id, t.description, t.due_date, g.name AS group_name
       FROM tasks t
       INNER JOIN groups g ON g.id = t.group_id AND COALESCE(g.active,1)=1 AND COALESCE(g.archived,0)=0 AND COALESCE(g.is_community,0)=0
       INNER JOIN group_members gm ON gm.group_id = t.group_id AND gm.user_id = ? AND gm.is_active = 1
       INNER JOIN allowed_groups ag ON ag.group_id = t.group_id AND ag.status = 'allowed'
       WHERE 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.user_id, startYmd, endYmd) as Array<{ id: number; description: string; due_date: string; group_name: string | null }>;

  const events = tasks.map((t) => ({
    id: t.id,
    description: t.description,
    due_date: t.due_date,
    group_name: t.group_name || null,
    prefix: 'T'
  }));

  const { body, etag } = await buildIcsCalendar('Wtask.org Tareas – Agregado', events);

  // 304 si ETag coincide
  const inm = request.headers.get('if-none-match');
  if (inm && inm === etag) {
    return new Response(null, { status: 304, headers: { ETag: etag, 'Cache-Control': 'public, max-age=300' } });
  }

  db.prepare(`UPDATE calendar_tokens SET last_used_at = ? WHERE id = ?`).run(toIsoSqlUTC(), row.id);

  return new Response(body, {
    status: 200,
    headers: {
      'content-type': 'text/calendar; charset=utf-8',
      'cache-control': 'public, max-age=300',
      ETag: etag
    }
  });
};
