import { describe, it, expect, beforeAll, afterAll } from 'bun:test';
import { Database } from 'bun:sqlite';
import { initializeDatabase } from '../../src/db';
import { setDb, getDb } from '../../src/db/locator';
import { TaskService } from '../../src/tasks/service';
import { ResponseQueue } from '../../src/services/response-queue';

describe('Locator fallback - servicios usan getDb() cuando no hay dbInstance', () => {
  let memdb: Database;
  let prevDb: Database | null = null;
  let hadPrev = false;
  let originalEnv: NodeJS.ProcessEnv;
  let originalTaskDb: any;
  let originalQueueDb: any;

  beforeAll(() => {
    originalEnv = { ...process.env };
    process.env.NODE_ENV = 'test';
    process.env.CHATBOT_PHONE_NUMBER = '999999';

    // Capturar DB previa del locator (si la hubiera)
    try {
      prevDb = getDb();
      hadPrev = true;
    } catch {
      prevDb = null;
      hadPrev = false;
    }

    // Crear DB de pruebas y configurarla en el locator global
    memdb = new Database(':memory:');
    initializeDatabase(memdb);
    setDb(memdb);

    // Forzar fallback deshabilitando las instancias estáticas
    originalTaskDb = (TaskService as any).dbInstance;
    (TaskService as any).dbInstance = undefined;

    originalQueueDb = (ResponseQueue as any).dbInstance;
    (ResponseQueue as any).dbInstance = undefined;
  });

  afterAll(() => {
    // Restaurar instancias estáticas
    try { (TaskService as any).dbInstance = originalTaskDb; } catch {}
    try { (ResponseQueue as any).dbInstance = originalQueueDb; } catch {}

    // Restaurar locator previo si existía; si no, dejamos memdb viva sin cerrar
    if (hadPrev && prevDb) {
      try { setDb(prevDb); } catch {}
      try { memdb.close(); } catch {}
    }

    process.env = originalEnv;
  });

  it('TaskService.createTask y countAllActive funcionan vía locator', () => {
    const createdBy = '34600123456';
    const taskId = TaskService.createTask(
      { description: 'Locator smoke', due_date: null, group_id: null, created_by: createdBy },
      []
    );
    expect(typeof taskId).toBe('number');
    expect(taskId).toBeGreaterThan(0);

    const cnt = TaskService.countAllActive();
    expect(cnt).toBe(1);
  });

  it('ResponseQueue.add persiste en DB vía locator', async () => {
    await ResponseQueue.add([{ recipient: '321', message: 'hola locator' }]);
    const row = memdb.query(`SELECT COUNT(*) AS c FROM response_queue`).get() as any;
    expect(Number(row?.c || 0)).toBe(1);
  });
});
