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 || '', 'personal');
  if (res instanceof Response) return res;
  const { row } = res;

  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
       LEFT JOIN group_members gm ON gm.group_id = t.group_id AND gm.user_id = ? AND gm.is_active = 1
       LEFT 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 EXISTS (SELECT 1 FROM task_assignments a WHERE a.task_id = t.id AND a.user_id = ?)
         AND (t.group_id IS NULL OR (gm.user_id IS NOT NULL AND ag.group_id IS NOT NULL AND COALESCE(g.active,1)=1 AND COALESCE(g.is_community,0)=0 AND COALESCE(g.archived,0)=0))
       ORDER BY t.due_date ASC, t.id ASC`
    )
    .all(row.user_id, startYmd, endYmd, row.user_id) as any[];

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