import { describe, it, expect, beforeAll, beforeEach } from 'bun:test';
import { Database } from 'bun:sqlite';
import { initializeDatabase } from '../../../src/db';
import { TaskService } from '../../../src/tasks/service';
import { CommandService } from '../../../src/services/command';
import { GroupSyncService } from '../../../src/services/group-sync';
import { setDb } from '../../../src/db/locator';

describe('CommandService - inserta task_origins al crear en grupo con messageId', () => {
  let memdb: Database;

  beforeAll(() => {
    memdb = new Database(':memory:');
    initializeDatabase(memdb);
    setDb(memdb);

    // Sembrar grupo activo y cache
    memdb.exec(`
      INSERT OR IGNORE INTO groups (id, community_id, name, active, archived, is_community, last_verified)
      VALUES ('g1@g.us', 'comm-1', 'G1', 1, 0, 0, strftime('%Y-%m-%d %H:%M:%f','now'))
    `);
    try { (GroupSyncService as any).dbInstance = memdb; } catch {}
    GroupSyncService.activeGroupsCache?.clear?.();
    GroupSyncService.activeGroupsCache?.set?.('g1@g.us', 'G1');
  });

  beforeEach(() => {
    process.env.NODE_ENV = 'test';
    memdb.exec('DELETE FROM task_assignments; DELETE FROM tasks; DELETE FROM task_origins;');
  });

  it('crea tarea en grupo y registra (task_id, chat_id, message_id)', async () => {
    const sender = '600111222';
    const res = await CommandService.handle({
      sender,
      groupId: 'g1@g.us',
      message: 't n pruebas origen 2099-01-05',
      mentions: [],
      messageId: 'MSG-ORIG-1'
    });

    expect(res.length).toBeGreaterThan(0);

    const t = memdb.prepare(`SELECT id FROM tasks ORDER BY id DESC LIMIT 1`).get() as any;
    expect(t).toBeTruthy();
    const row = memdb.prepare(`
      SELECT task_id, chat_id, message_id FROM task_origins WHERE task_id = ?
    `).get(Number(t.id)) as any;

    expect(row).toBeTruthy();
    expect(Number(row.task_id)).toBe(Number(t.id));
    expect(String(row.chat_id)).toBe('g1@g.us');
    expect(String(row.message_id)).toBe('MSG-ORIG-1');
  });
});
