import { describe, it, beforeEach, afterEach, expect } from 'bun:test';
import Database from 'bun:sqlite';
import { initializeDatabase } from '../../../src/db';
import { TaskService } from '../../../src/tasks/service';
import { AllowedGroups } from '../../../src/services/allowed-groups';
import { setDb, resetDb } from '../../../src/db/locator';
import { seedGroup } from '../../helpers/db';

describe('TaskService - gating en creación con group_id (enforce)', () => {
  const envBackup = process.env;
  let memdb: Database;

  beforeEach(() => {
    process.env = { ...envBackup, NODE_ENV: 'test', GROUP_GATING_MODE: 'enforce' };
    memdb = new Database(':memory:');
    initializeDatabase(memdb);
    setDb(memdb);
  });

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

  it('fuerza group_id=null cuando el grupo no está allowed', () => {
    const gid = 'na@g.us';
    seedGroup(memdb, gid);
    AllowedGroups.setStatus(gid, 'blocked');

    const taskId = TaskService.createTask(
      {
        description: 'Probar gating',
        due_date: null,
        group_id: gid,
        created_by: '34600123456',
      },
      [{ user_id: '34600123456', assigned_by: '34600123456' }]
    );

    const row = memdb
      .query(`SELECT group_id FROM tasks WHERE id = ?`)
      .get(taskId) as any;
    expect(row?.group_id).toBeNull();
  });

  it('conserva group_id cuando el grupo está allowed', () => {
    const gid = 'ok@g.us';
    seedGroup(memdb, gid);
    AllowedGroups.setStatus(gid, 'allowed');

    const taskId = TaskService.createTask(
      {
        description: 'Tarea en grupo allowed',
        due_date: null,
        group_id: gid,
        created_by: '34600123456',
      },
      [{ user_id: '34600123456', assigned_by: '34600123456' }]
    );

    const row = memdb
      .query(`SELECT group_id FROM tasks WHERE id = ?`)
      .get(taskId) as any;
    expect(String(row?.group_id)).toBe(gid);
  });
});
