import { describe, test, expect, beforeEach, afterEach } from 'bun:test';
import { WebhookServer } from '../../src/server';
import { GroupSyncService } from '../../src/services/group-sync';

const envBackup = { ...process.env };

describe('WebhookServer - evento GROUPS_UPSERT', () => {
  let originalSyncGroups: any;
  let originalRefresh: any;
  let originalSyncMembers: any;

  beforeEach(() => {
    process.env = { ...envBackup, NODE_ENV: 'test' }; // omite verificación de instancia
    originalSyncGroups = GroupSyncService.syncGroups;
    originalRefresh = (GroupSyncService as any).refreshActiveGroupsCache;
    originalSyncMembers = GroupSyncService.syncMembersForActiveGroups;
  });

  afterEach(() => {
    GroupSyncService.syncGroups = originalSyncGroups;
    (GroupSyncService as any).refreshActiveGroupsCache = originalRefresh;
    GroupSyncService.syncMembersForActiveGroups = originalSyncMembers;
    process.env = envBackup;
  });

  test('dispara syncGroups -> refresh -> syncMembers', async () => {
    const calls: string[] = [];
    GroupSyncService.syncGroups = async () => {
      calls.push('syncGroups');
      return { added: 0, updated: 0 };
    };
    (GroupSyncService as any).refreshActiveGroupsCache = () => {
      calls.push('refresh');
    };
    GroupSyncService.syncMembersForActiveGroups = async () => {
      calls.push('syncMembers');
      return { groups: 0, added: 0, updated: 0, deactivated: 0 };
    };

    const payload = {
      event: 'GROUPS_UPSERT',
      instance: 'any-instance',
      data: {}
    };
    const req = new Request('http://localhost:3007', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(payload)
    });

    const res = await WebhookServer.handleRequest(req);
    expect(res.status).toBe(200);
    expect(calls).toEqual(['syncGroups', 'refresh', 'syncMembers']);
  });
});
