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 - personal feed', () => {
  const PORT = 19132;
  const BASE = `http://127.0.0.1:${PORT}`;
  const USER = '34600123456';
  const GROUP_ALLOWED = '111@g.us';
  const GROUP_BLOCKED = '222@g.us';
  const SID = 'sid-ics-personal-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_ALLOWED}', 'comm1', 'Allowed', 1)`
  );
  db.exec(
    `INSERT OR IGNORE INTO groups (id, community_id, name, active) VALUES ('${GROUP_BLOCKED}', 'comm2', 'Blocked', 1)`
  );
  db.exec(
    `INSERT OR IGNORE INTO allowed_groups (group_id, status, discovered_at, updated_at) VALUES ('${GROUP_ALLOWED}', 'allowed', '${toIsoSql()}', '${toIsoSql()}')`
  );
  db.exec(
    `INSERT OR IGNORE INTO allowed_groups (group_id, status, discovered_at, updated_at) VALUES ('${GROUP_BLOCKED}', 'blocked', '${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_ALLOWED}', '${USER}', 0, 1, '${toIsoSql()}', '${toIsoSql()}')`
  );

  const today = new Date();
  const dueIn2 = ymdUTC(addDays(today, 2));
  const dueIn5 = ymdUTC(addDays(today, 5));
  const duePast = ymdUTC(addDays(today, -2));

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

  // Privada asignada (incluida)
  const r1 = insTask.run('Private assigned', dueIn2, null, createdBy, 0, toIsoSql());
  const t1 = Number(r1.lastInsertRowid);
  db.prepare(`INSERT INTO task_assignments (task_id, user_id, assigned_by, assigned_at)
              VALUES (?, ?, ?, ?)`).run(t1, USER, USER, toIsoSql());

  // Grupo allowed asignada (incluida)
  const r2 = insTask.run('Allowed group assigned', dueIn5, GROUP_ALLOWED, 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());

  // Grupo blocked asignada (excluida)
  const r3 = insTask.run('Blocked group assigned', dueIn5, GROUP_BLOCKED, createdBy, 0, toIsoSql());
  const t3 = Number(r3.lastInsertRowid);
  db.prepare(`INSERT INTO task_assignments (task_id, user_id, assigned_by, assigned_at)
              VALUES (?, ?, ?, ?)`).run(t3, USER, USER, toIsoSql());

  // Grupo allowed sin due_date (excluida)
  const r4 = insTask.run('No due date', null, GROUP_ALLOWED, createdBy, 0, toIsoSql());
  const t4 = Number(r4.lastInsertRowid);
  db.prepare(`INSERT INTO task_assignments (task_id, user_id, assigned_by, assigned_at)
              VALUES (?, ?, ?, ?)`).run(t4, USER, USER, toIsoSql());

  // Grupo allowed completada (excluida)
  const r5 = insTask.run('Completed assigned', dueIn2, GROUP_ALLOWED, createdBy, 1, toIsoSql());
  const t5 = Number(r5.lastInsertRowid);
  db.prepare(`INSERT INTO task_assignments (task_id, user_id, assigned_by, assigned_at)
              VALUES (?, ?, ?, ?)`).run(t5, USER, USER, toIsoSql());

  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 personal 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-personal', '${USER}', '${sidHash}', '${toIsoSql()}', '${toIsoSql()}', '${toIsoSql(
      addDays(new Date(), 1)
    )}')
    `);

    // Obtener URLs de feeds
    const resFeeds = await fetch(`${BASE}/api/integrations/feeds`, {
      headers: { cookie: `sid=${SID}` },
    });
    expect(resFeeds.status).toBe(200);
    const feeds = await resFeeds.json();
    expect(feeds.personal && typeof feeds.personal.url === 'string').toBe(true);

    const personalUrl: string = feeds.personal.url;
    const token = new URL(personalUrl).pathname.split('/').pop()!.replace(/\.ics$/i, '');

    // Primera petición ICS
    const resIcs = await fetch(personalUrl);
    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 y t2
    expect(body1.includes(`[T${pad4(t1)}]`)).toBe(true);
    expect(body1.includes(`[T${pad4(t2)}]`)).toBe(true);

    // Excluidos
    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') || '';
    const res304 = await fetch(personalUrl, { headers: { 'if-none-match': etag } });
    expect(res304.status).toBe(304);

    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();

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