import type { RequestHandler } from './$types';
import { getDb } from '$lib/server/db';
import { findActiveToken, createCalendarTokenUrl, buildCalendarIcsUrl, rotateCalendarTokenUrl } from '$lib/server/calendar-tokens';
import { fetchAllowedUserGroups } from '$lib/server/task-helpers';

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

  const db = await getDb();

  // Listar solo grupos permitidos donde el usuario está activo (excluye comunidad y archivados)
  const groups = fetchAllowedUserGroups(db, userId, { excludeCommunityArchived: true });

  // Personal
  const personalExisting = await findActiveToken('personal', userId, null);
  const personal = await (async () => {
    if (personalExisting) {
      if (personalExisting.token_plain) {
        return { url: buildCalendarIcsUrl('personal', personalExisting.token_plain) };
      }
      const rotated = await rotateCalendarTokenUrl('personal', userId, null);
      return { url: rotated.url };
    } else {
      const created = await createCalendarTokenUrl('personal', userId, null);
      return { url: created.url };
    }
  })();

  // Aggregate (multigrupo)
  const aggregateExisting = await findActiveToken('aggregate', userId, null);
  const aggregate = await (async () => {
    if (aggregateExisting) {
      if (aggregateExisting.token_plain) {
        return { url: buildCalendarIcsUrl('aggregate', aggregateExisting.token_plain) };
      }
      const rotated = await rotateCalendarTokenUrl('aggregate', userId, null);
      return { url: rotated.url };
    } else {
      const created = await createCalendarTokenUrl('aggregate', userId, null);
      return { url: created.url };
    }
  })();

  // Por grupo (B): autogenerar si falta
  const groupFeeds: Array<{ groupId: string; groupName: string | null; url: string | null }> = [];
  for (const g of groups) {
    const ex = await findActiveToken('group', userId, g.id);
    if (ex) {
      let url: string | null;
      if (ex.token_plain) {
        url = buildCalendarIcsUrl('group', ex.token_plain);
      } else {
        const rotated = await rotateCalendarTokenUrl('group', userId, g.id);
        url = rotated.url;
      }
      groupFeeds.push({ groupId: g.id, groupName: g.name ?? null, url });
    } else {
      const created = await createCalendarTokenUrl('group', userId, g.id);
      groupFeeds.push({ groupId: g.id, groupName: g.name ?? null, url: created.url });
    }
  }

  const body = {
    personal,
    groups: groupFeeds,
    aggregate
  };

  return new Response(JSON.stringify(body), {
    status: 200,
    headers: { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' }
  });
};
