import { describe, it, expect, afterAll } from 'bun:test';
import Database from 'bun:sqlite';
import { startWebServer } from './helpers/server';
import { createTempDb } from './helpers/db';

import { sha256Hex } from '../helpers/crypto';

import { toIsoSql, ymdUTC, addDays } from '../helpers/dates';



function pad4(n: number): string {
  const s = String(Math.floor(n));
  return s.length >= 4 ? s : '0'.repeat(4 - s.length) + s;
}

describe('ICS - group feed', () => {
  const PORT = 19131;
  const BASE = `http://127.0.0.1:${PORT}`;
  const USER = '34600123456';
  const GROUP = '123@g.us';
  const SID = 'sid-ics-group-1';

  const tmp = createTempDb();
  const db: any = tmp.db as Database;

  // Sembrar datos mínimos
  db.exec(`INSERT OR IGNORE INTO users (id) VALUES ('${USER}')`);
  db.exec(
    `INSERT OR IGNORE INTO groups (id, community_id, name, active) VALUES ('${GROUP}', 'comm1', 'Group One', 1)`
  );
  db.exec(
    `INSERT OR IGNORE INTO allowed_groups (group_id, status, discovered_at, updated_at) VALUES ('${GROUP}', 'allowed', '${toIsoSql()}', '${toIsoSql()}')`
  );
  db.exec(
    `INSERT OR IGNORE INTO group_members (group_id, user_id, is_admin, is_active, first_seen_at, last_seen_at)
     VALUES ('${GROUP}', '${USER}', 0, 1, '${toIsoSql()}', '${toIsoSql()}')`
  );

  // Tareas del grupo (varias condiciones)
  const today = new Date();
  const dueIn2 = ymdUTC(addDays(today, 2));
  const dueIn400 = ymdUTC(addDays(today, 400));

  const insTask = db.prepare(
    `INSERT INTO tasks (description, due_date, group_id, created_by, completed, created_at)
     VALUES (?, ?, ?, ?, ?, ?)`
  );
  const createdBy = USER;

  // t1: sin responsable, dentro de horizonte -> debe aparecer
  const r1 = insTask.run('Task unassigned in range', dueIn2, GROUP, createdBy, 0, toIsoSql());
  const t1 = Number(r1.lastInsertRowid);

  // t2: con responsable -> NO debe aparecer
  const r2 = insTask.run('Task assigned', dueIn2, GROUP, createdBy, 0, toIsoSql());
  const t2 = Number(r2.lastInsertRowid);
  db.prepare(`INSERT INTO task_assignments (task_id, user_id, assigned_by, assigned_at)
              VALUES (?, ?, ?, ?)`).run(t2, USER, USER, toIsoSql());

  // t3: completada -> NO debe aparecer
  const r3 = insTask.run('Task completed', dueIn2, GROUP, createdBy, 1, toIsoSql());
  const t3 = Number(r3.lastInsertRowid);

  // t4: muy lejos (fuera de horizonte) -> NO debe aparecer
  const r4 = insTask.run('Task far future', dueIn400, GROUP, createdBy, 0, toIsoSql());
  const t4 = Number(r4.lastInsertRowid);

  // t5: sin due_date -> NO debe aparecer
  const r5 = insTask.run('Task without due', null, GROUP, createdBy, 0, toIsoSql());
  const t5 = Number(r5.lastInsertRowid);

  const sidHashPromise = sha256Hex(SID);
  const serverPromise = startWebServer({
    port: PORT,
    env: {
      DB_PATH: tmp.path,
      WEB_BASE_URL: BASE,
    },
  });

  let server: Awaited<typeof serverPromise> | null = null;

  afterAll(async () => {
    try {
      await server?.stop();
    } catch {}
    try {
      tmp.cleanup();
    } catch {}
  });

  it('serves ICS for group token with correct filtering, supports ETag, and returns 410 when revoked', async () => {
    server = await serverPromise;

    const sidHash = await sidHashPromise;
    db.exec(`
      INSERT OR REPLACE INTO web_sessions (id, user_id, session_hash, created_at, last_seen_at, expires_at)
      VALUES ('sess-ics-group', '${USER}', '${sidHash}', '${toIsoSql()}', '${toIsoSql()}', '${toIsoSql(
      addDays(new Date(), 1)
    )}')
    `);

    // Obtener URLs de feeds (autogenera tokens)
    const resFeeds = await fetch(`${BASE}/api/integrations/feeds`, {
      headers: { cookie: `sid=${SID}` },
    });
    expect(resFeeds.status).toBe(200);
    const feeds = await resFeeds.json();
    const groupItem = (feeds.groups || []).find((g: any) => g.groupId === GROUP);
    expect(groupItem && typeof groupItem.url === 'string' && groupItem.url.endsWith('.ics')).toBe(true);

    const groupUrl = groupItem.url as string;
    const token = new URL(groupUrl).pathname.split('/').pop()!.replace(/\.ics$/i, '');

    // Primera petición ICS
    const resIcs = await fetch(groupUrl);
    expect(resIcs.status).toBe(200);
    expect((resIcs.headers.get('content-type') || '').includes('text/calendar')).toBe(true);
    const body1 = await resIcs.text();

    // Debe contener solo t1
    expect(body1.includes(`[T${pad4(t1)}]`)).toBe(true);
    expect(body1.includes(`[T${pad4(t2)}]`)).toBe(false);
    expect(body1.includes(`[T${pad4(t3)}]`)).toBe(false);
    expect(body1.includes(`[T${pad4(t4)}]`)).toBe(false);
    expect(body1.includes(`[T${pad4(t5)}]`)).toBe(false);

    const etag = resIcs.headers.get('etag') || '';

    // Segunda petición con If-None-Match -> 304
    const res304 = await fetch(groupUrl, { headers: { 'if-none-match': etag } });
    expect(res304.status).toBe(304);

    // last_used_at actualizado
    const row = db
      .prepare(`SELECT last_used_at FROM calendar_tokens WHERE token_plain = ?`)
      .get(token) as any;
    expect(row && row.last_used_at).toBeTruthy();

    // Revocar el token y comprobar 410
    db.prepare(`UPDATE calendar_tokens SET revoked_at = ? WHERE token_plain = ?`).run(toIsoSql(), token);
    const resGone = await fetch(groupUrl);
    expect(resGone.status).toBe(410);
  });
});
