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 { setDb } from '../../../src/db/locator';

describe('CommandService - asignación por defecto (sin dueño vs creador)', () => {
  let memdb: Database;

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

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

  it('en grupos, si no hay menciones, la tarea queda sin dueño', async () => {
    const sender = '600111222';
    await CommandService.handle({
      sender,
      groupId: '12345@g.us', // contexto grupo
      message: 't n tarea en grupo',
      mentions: [],
    });

    const t = memdb.prepare(`SELECT id FROM tasks ORDER BY id DESC LIMIT 1`).get() as any;
    const cnt = memdb.prepare(`SELECT COUNT(*) as c FROM task_assignments WHERE task_id = ?`).get(t.id) as any;
    expect(Number(cnt.c)).toBe(0);
  });

  it('en DM, si no hay menciones, se asigna al creador', async () => {
    const sender = '600111222';
    await CommandService.handle({
      sender,
      groupId: `${sender}@s.whatsapp.net`, // DM
      message: 't n tarea en dm',
      mentions: [],
    });

    const t = memdb.prepare(`SELECT id FROM tasks ORDER BY id DESC LIMIT 1`).get() as any;
    const row = memdb.prepare(`SELECT user_id FROM task_assignments WHERE task_id = ?`).get(t.id) as any;
    expect(row).toBeTruthy();
    expect(String(row.user_id)).toBe(sender);
  });
});
