import { describe, test, expect, beforeEach, afterEach } from 'bun:test';
import { Database } from 'bun:sqlite';
import { initializeDatabase } from '../../../src/db';
import { MaintenanceService } from '../../../src/services/maintenance';

import { toIsoSql as toIso } from '../../helpers/dates';

const envBackup = { ...process.env };
let memdb: Database;

describe('MaintenanceService - cleanup de miembros inactivos', () => {
  beforeEach(() => {
    process.env = { ...envBackup, NODE_ENV: 'test' };
    memdb = new Database(':memory:');
    initializeDatabase(memdb);

    memdb.exec(`INSERT INTO users (id) VALUES ('u1'), ('u2'), ('u3')`);
    memdb.exec(`INSERT INTO groups (id, community_id, name, active, last_verified) VALUES ('g1@g.us','comm','G1',1, ?)`, toIso(new Date()));
  });

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

  test('elimina inactivos con last_seen_at más viejo que el umbral', async () => {
    const old = new Date(Date.now() - 200 * 24 * 60 * 60 * 1000); // 200 días
    const recent = new Date(Date.now() - 50 * 24 * 60 * 60 * 1000); // 50 días
    const now = new Date();

    // Sembrar miembros: dos inactivos (uno viejo, uno reciente) y uno activo
    memdb.exec(`INSERT INTO group_members (group_id, user_id, is_admin, is_active, first_seen_at, last_seen_at) VALUES 
      ('g1@g.us','u1',0,0,?,?),
      ('g1@g.us','u2',0,0,?,?),
      ('g1@g.us','u3',0,1,?,?)`,
      toIso(old), toIso(old),
      toIso(recent), toIso(recent),
      toIso(now), toIso(now)
    );

    const before = memdb.prepare(`SELECT COUNT(*) AS c FROM group_members WHERE is_active = 0`).get() as any;
    expect(Number(before.c)).toBe(2);

    const deleted = await MaintenanceService.cleanupInactiveMembersOnce(memdb, 180);
    expect(deleted).toBe(1);

    const after = memdb.prepare(`SELECT COUNT(*) AS c FROM group_members WHERE is_active = 0`).get() as any;
    expect(Number(after.c)).toBe(1);
  });
});
