import { describe, it, beforeEach, expect } from 'bun:test';
import { makeMemDb } from '../../helpers/db';
import { AdminService } from '../../../src/services/admin';
import { AllowedGroups } from '../../../src/services/allowed-groups';
import { setDb } from '../../../src/db/locator';

describe('AdminService - comandos básicos', () => {
  const envBackup = process.env;
  let memdb: any;

  beforeEach(() => {
    process.env = { ...envBackup, NODE_ENV: 'test', ADMIN_USERS: '34600123456' };
    memdb = makeMemDb();
    setDb(memdb);
    AllowedGroups.resetForTests();
  });

  it('rechaza a usuarios no admin', async () => {
    const out = await AdminService.handle({
      sender: '34999888777',
      groupId: 'g1@g.us',
      message: '/admin pendientes'
    });
    expect(out.length).toBe(1);
    expect(out[0].message.toLowerCase()).toContain('no estás autorizado');
  });

  it('lista pendientes', async () => {
    AllowedGroups.upsertPending('a@g.us', 'A', 'tester');
    AllowedGroups.upsertPending('b@g.us', 'B', 'tester');

    const out = await AdminService.handle({
      sender: '34600123456',
      groupId: 'g1@g.us',
      message: '/admin pendientes'
    });

    expect(out.length).toBe(1);
    expect(out[0].message).toContain('Grupos pendientes');
    expect(out[0].message).toContain('a@g.us');
    expect(out[0].message).toContain('b@g.us');
  });

  it('habilitar-aquí en grupo', async () => {
    const out = await AdminService.handle({
      sender: '34600123456',
      groupId: 'g1@g.us',
      message: '/admin habilitar-aquí'
    });
    expect(out.length).toBe(1);
    expect(AllowedGroups.isAllowed('g1@g.us')).toBe(true);
  });

  it('allow-group <jid> habilita explícitamente', async () => {
    const out = await AdminService.handle({
      sender: '34600123456',
      groupId: '1234567890@s.whatsapp.net',
      message: '/admin allow-group g2@g.us'
    });
    expect(out.length).toBe(1);
    expect(AllowedGroups.isAllowed('g2@g.us')).toBe(true);
  });

  it('archivar-aquí: marca archived=1, active=0; revoca tokens; desactiva membresías; bloquea allowed_groups', async () => {
    // Sembrar grupo, token, membresía y allowed
    memdb.exec(`INSERT INTO groups (id, community_id, name, active, archived, last_verified) VALUES ('g1@g.us','comm-1','G1',1,0,strftime('%Y-%m-%d %H:%M:%f','now'))`);
    memdb.exec(`INSERT INTO allowed_groups (group_id, status, discovered_at, updated_at) VALUES ('g1@g.us','allowed',strftime('%Y-%m-%d %H:%M:%f','now'),strftime('%Y-%m-%d %H:%M:%f','now'))`);
    memdb.exec(`INSERT INTO users (id, first_seen, last_seen) VALUES ('34600123456',strftime('%Y-%m-%d %H:%M:%f','now'),strftime('%Y-%m-%d %H:%M:%f','now'))`);
    memdb.exec(`INSERT INTO calendar_tokens (type, user_id, group_id, token_hash, created_at) VALUES ('group','34600123456','g1@g.us','h1',strftime('%Y-%m-%d %H:%M:%f','now'))`);
    memdb.exec(`INSERT INTO group_members (group_id, user_id, is_admin, is_active, first_seen_at, last_seen_at) VALUES ('g1@g.us','34600123456',0,1,strftime('%Y-%m-%d %H:%M:%f','now'),strftime('%Y-%m-%d %H:%M:%f','now'))`);

    const out = await AdminService.handle({
      sender: '34600123456',
      groupId: 'g1@g.us',
      message: '/admin archivar-aquí'
    });
    expect(out.length).toBe(1);

    const g = memdb.query(`SELECT active, archived FROM groups WHERE id='g1@g.us'`).get() as any;
    expect(Number(g.active)).toBe(0);
    expect(Number(g.archived)).toBe(1);

    const tok = memdb.query(`SELECT revoked_at FROM calendar_tokens WHERE group_id='g1@g.us'`).get() as any;
    expect(tok && tok.revoked_at).toBeTruthy();

    const gm = memdb.query(`SELECT is_active FROM group_members WHERE group_id='g1@g.us'`).get() as any;
    expect(Number(gm.is_active)).toBe(0);

    // allowed_groups bloqueado
    const ag = memdb.query(`SELECT status FROM allowed_groups WHERE group_id='g1@g.us'`).get() as any;
    expect(String(ag.status)).toBe('blocked');
  });

  it('borrar-aquí: borra tasks, assignments, grupo y allowed_groups', async () => {
    memdb.exec(`INSERT INTO groups (id, community_id, name, active) VALUES ('g2@g.us','comm-1','G2',1)`);
    memdb.exec(`INSERT INTO allowed_groups (group_id, status, discovered_at, updated_at) VALUES ('g2@g.us','allowed',strftime('%Y-%m-%d %H:%M:%f','now'),strftime('%Y-%m-%d %H:%M:%f','now'))`);
    memdb.exec(`INSERT INTO users (id, first_seen, last_seen) VALUES ('34600123456',strftime('%Y-%m-%d %H:%M:%f','now'),strftime('%Y-%m-%d %H:%M:%f','now'))`);
    const r1 = memdb.query(`INSERT INTO tasks (description, group_id, created_by) VALUES ('t1','g2@g.us','34600123456') RETURNING id`).get() as any;
    const r2 = memdb.query(`INSERT INTO tasks (description, group_id, created_by) VALUES ('t2','g2@g.us','34600123456') RETURNING id`).get() as any;
    memdb.exec(`INSERT INTO task_assignments (task_id, user_id, assigned_by) VALUES (${Number(r1.id)}, '34600123456', '34600123456')`);
    memdb.exec(`INSERT INTO task_assignments (task_id, user_id, assigned_by) VALUES (${Number(r2.id)}, '34600123456', '34600123456')`);

    const out = await AdminService.handle({
      sender: '34600123456',
      groupId: 'g2@g.us',
      message: '/admin borrar-aquí'
    });
    expect(out.length).toBe(1);

    const tcount = memdb.query(`SELECT COUNT(*) AS c FROM tasks WHERE group_id='g2@g.us'`).get() as any;
    expect(Number(tcount.c)).toBe(0);

    const g = memdb.query(`SELECT 1 FROM groups WHERE id='g2@g.us'`).get() as any;
    expect(g == null).toBe(true);

    const ag = memdb.query(`SELECT 1 FROM allowed_groups WHERE group_id='g2@g.us'`).get() as any;
    expect(ag == null).toBe(true);

    const acount = memdb.query(`SELECT COUNT(*) AS c FROM task_assignments`).get() as any;
    expect(Number(acount.c)).toBe(0);
  });
});
