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

describe('CommandService - gating en modo enforce', () => {
  const envBackup = process.env;
  let memdb: any;

  beforeEach(() => {
    process.env = { ...envBackup, NODE_ENV: 'test', GROUP_GATING_MODE: 'enforce' };
    memdb = makeMemDb();
    setDb(memdb);
    try { AllowedGroups.resetForTests(); } catch {}
  });

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

  it('bloquea comandos en grupo no permitido (desconocido)', async () => {
    const res = await CommandService.handle({
      sender: '34600123456',
      groupId: 'g1@g.us',
      message: 't ayuda',
      mentions: []
    });
    expect(Array.isArray(res)).toBe(true);
    expect(res.length).toBe(0);
  });

  it('permite comandos en grupo permitido', async () => {
    AllowedGroups.setStatus('g2@g.us', 'allowed', 'G2');

    const res = await CommandService.handle({
      sender: '34600123456',
      groupId: 'g2@g.us',
      message: 't ayuda',
      mentions: []
    });

    expect(res.length).toBeGreaterThan(0);
    expect(res[0].recipient).toBe('34600123456');
  });
});
