import Database from 'bun:sqlite';
import { initializeDatabase, ensureUserExists } from '../../../src/db';
import { AdminService } from '../../../src/services/admin';
import { TaskService } from '../../../src/tasks/service';
import { setDb, resetDb } from '../../../src/db/locator';

describe('AdminService - /admin ver todos', () => {
  let memdb: Database;
  const ADMIN = '34600123456';
  const OTHER = '34999999999';

  beforeEach(() => {
    process.env.NODE_ENV = 'test';
    process.env.GROUP_GATING_MODE = 'off';
    process.env.ADMIN_USERS = ADMIN;

    memdb = new Database(':memory:');
    initializeDatabase(memdb);
    setDb(memdb);
    (AdminService as any).dbInstance = memdb;
    (TaskService as any).dbInstance = memdb;

    // seed groups
    memdb.prepare(`
      INSERT INTO groups (id, community_id, name, active, last_verified)
      VALUES ('g1@g.us', 'comm', 'Grupo Uno', 1, strftime('%Y-%m-%d %H:%M:%f','now'))
    `).run();
    memdb.prepare(`
      INSERT INTO groups (id, community_id, name, active, last_verified)
      VALUES ('g2@g.us', 'comm', 'Grupo Dos', 1, strftime('%Y-%m-%d %H:%M:%f','now'))
    `).run();

    // seed tasks
    const creator = ensureUserExists(ADMIN, memdb)!;
    TaskService.createTask({ description: 'Alpha', due_date: '2025-10-10', group_id: 'g1@g.us', created_by: creator }, []);
    TaskService.createTask({ description: 'Beta', due_date: '2025-10-05', group_id: 'g2@g.us', created_by: creator }, []);
    TaskService.createTask({ description: 'Gamma', due_date: null, group_id: 'g1@g.us', created_by: creator }, []);
  });

  afterEach(() => {
    resetDb();
    try { memdb.close(); } catch {}
  });

  it('lista todas las tareas activas y responde por DM al admin', async () => {
    const res = await AdminService.handle({
      sender: ADMIN,
      groupId: 'g1@g.us',
      message: '/admin ver todos'
    });
    expect(res.length).toBe(1);
    expect(res[0].recipient).toBe(ADMIN);
    expect(res[0].message).toContain('Tareas activas');
    expect(res[0].message).toContain('Alpha');
    expect(res[0].message).toContain('Beta');
    expect(res[0].message).toContain('Gamma');
  });

  it('respeta un límite numérico y menciona truncado cuando aplica', async () => {
    const res = await AdminService.handle({
      sender: ADMIN,
      groupId: 'g1@g.us',
      message: '/admin ver todos 2'
    });
    expect(res.length).toBe(1);
    expect(res[0].recipient).toBe(ADMIN);
    expect(res[0].message).toContain('mostrando 2');
  });

  it('rechaza usuarios no autorizados', async () => {
    process.env.ADMIN_USERS = ADMIN; // sigue igual, pero probamos otro sender
    const res = await AdminService.handle({
      sender: OTHER,
      groupId: 'g1@g.us',
      message: '/admin ver todos'
    });
    expect(res.length).toBe(1);
    expect(res[0].message).toContain('No estás autorizado');
  });
});
