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

describe('GroupSyncService - gating en scheduler de miembros (enforce)', () => {
  const envBackup = process.env;
  const calls: string[] = [];

  beforeEach(() => {
    process.env = { ...envBackup, NODE_ENV: 'ci', GROUP_GATING_MODE: 'enforce' };

    const memdb = makeMemDb();
    setDb(memdb);

    // Preparar caché de grupos activos (2 grupos: uno allowed y otro no)
    GroupSyncService.activeGroupsCache.clear();
    GroupSyncService.activeGroupsCache.set('ok@g.us', 'OK Group');
    GroupSyncService.activeGroupsCache.set('na@g.us', 'NA Group');

    // Sembrar allowed solo para 'ok@g.us'
    AllowedGroups.setStatus('ok@g.us', 'allowed', 'OK Group');

    // Stub de fetch para no hacer red y registrar llamadas
    (GroupSyncService as any).fetchGroupMembersFromAPI = async (gid: string) => {
      calls.push(gid);
      // Snapshot vacía para no escribir en DB
      return [];
    };
  });

  afterEach(() => {
    process.env = envBackup;
    calls.length = 0;
  });

  it('salta grupos no allowed y solo procesa los allowed', async () => {
    const summary = await GroupSyncService.syncMembersForActiveGroups();

    // Debe haber procesado solo 1 grupo (el allowed)
    expect(summary.groups).toBe(1);
    expect(calls).toEqual(['ok@g.us']);
    expect(calls).not.toContain('na@g.us');
  });
});
