import { describe, it, expect, beforeEach, afterEach } from 'bun:test';
import Database from 'bun:sqlite';
import { initializeDatabase } from '../../../src/db';
import { GroupSyncService } from '../../../src/services/group-sync';
import { setDb, resetDb } from '../../../src/db/locator';

describe('GroupSyncService - upsertGroups actualiza label en allowed_groups', () => {
  const envBackup = process.env;
  let memdb: Database;

  beforeEach(() => {
    process.env = { ...envBackup, NODE_ENV: 'test', WHATSAPP_COMMUNITY_ID: 'comm-1' };
    memdb = new Database(':memory:');
    initializeDatabase(memdb);
    setDb(memdb);

    // Limpiar tablas
    memdb.exec('DELETE FROM allowed_groups');
    memdb.exec('DELETE FROM groups');
  });

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

  it('propaga subject como label aunque no exista fila previa', async () => {
    await (GroupSyncService as any).upsertGroups([{ id: 'gg@g.us', subject: 'Grupo GG', linkedParent: 'comm-1' }]);

    const row = memdb.query(`SELECT label, status FROM allowed_groups WHERE group_id = 'gg@g.us'`).get() as any;
    expect(row).toBeDefined();
    expect(String(row.label)).toBe('Grupo GG');
    expect(String(row.status)).toBe('pending');
  });
});
