import type { RequestHandler } from './$types';
import { getDb } from '$lib/server/db';
import { rotateCalendarTokenUrl } from '$lib/server/calendar-tokens';
import { requireAuthAndJson } from '$lib/server/task-helpers';

export const POST: RequestHandler = async (event) => {
  const ctx = await requireAuthAndJson(event);
  if (ctx instanceof Response) return ctx;
  const { userId, payload } = ctx;

  const type = String(payload?.type || '').trim().toLowerCase();
  const groupId = payload?.groupId ? String(payload.groupId).trim() : null;

  if (!['personal', 'group', 'aggregate'].includes(type)) {
    return new Response(JSON.stringify({ error: 'type inválido' }), {
      status: 400,
      headers: { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' }
    });
  }

  // Validación de gating/membresía si es group
  if (type === 'group') {
    if (!groupId) {
      return new Response(JSON.stringify({ error: 'groupId requerido para type=group' }), {
        status: 400,
        headers: { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' }
      });
    }
    const db = await getDb();
    const row = db
      .prepare(
        `SELECT 1
         FROM groups g
         INNER JOIN group_members gm
           ON gm.group_id = g.id AND gm.user_id = ? AND gm.is_active = 1
         INNER JOIN allowed_groups ag
           ON ag.group_id = g.id AND ag.status = 'allowed'
         WHERE g.id = ? AND COALESCE(g.active, 1) = 1 AND COALESCE(g.is_community, 0) = 0 AND COALESCE(g.archived, 0) = 0
         LIMIT 1`
      )
      .get(userId, groupId) as any;
    if (!row) {
      return new Response(JSON.stringify({ error: 'forbidden' }), {
        status: 403,
        headers: { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' }
      });
    }
  }

  const rotated = await rotateCalendarTokenUrl(type as any, userId, groupId);
  return new Response(JSON.stringify({ url: rotated.url }), {
    status: 200,
    headers: { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' }
  });
};
