import { RoomResolver, RoomInfo } from '../../../../../src/modules/netaclaw/runtime/weixin_db/room_resolver.js';
import { createHash } from 'node:crypto';
import * as fs from 'node:fs';
import * as os from 'node:os';
import * as path from 'node:path';
import Database = require('better-sqlite3');

const tempDbs: string[] = [];
afterAll(() => {
  for (const file of tempDbs) {
    try { fs.rmSync(file, { force: true }); } catch { /* ignore */ }
  }
});

function tempDb(): string {
  const file = path.join(os.tmpdir(), `room-resolver-${Date.now()}-${Math.random()}.db`);
  tempDbs.push(file);
  return file;
}

describe('RoomResolver.filterWhitelistedGroupTables', () => {
  const h = (s: string) => 'Msg_' + createHash('md5').update(s, 'utf8').digest('hex');

  it('keeps only whitelist-matching group tables', () => {
    const r = new RoomResolver();
    const map = new Map<string, RoomInfo>([
      [h('gA@chatroom'), { tableName: h('gA@chatroom'), username: 'gA@chatroom', roomName: '产品研发群', isGroup: true }],
      [h('gB@chatroom'), { tableName: h('gB@chatroom'), username: 'gB@chatroom', roomName: '家庭群',     isGroup: true }],
      [h('wxid_dm1'),    { tableName: h('wxid_dm1'),    username: 'wxid_dm1',    roomName: '张三',       isGroup: false }],
    ]);
    r._setMap(map);
    const all = [h('gA@chatroom'), h('gB@chatroom'), h('wxid_dm1')];
    const whitelist = new Set(['产品研发群']);
    expect(r.filterWhitelistedGroupTables(all, whitelist)).toEqual([h('gA@chatroom')]);
  });

  it('returns empty when whitelist is empty', () => {
    const r = new RoomResolver();
    r._setMap(new Map([
      [h('g@chatroom'), { tableName: h('g@chatroom'), username: 'g@chatroom', roomName: '群', isGroup: true }],
    ]));
    expect(r.filterWhitelistedGroupTables([h('g@chatroom')], new Set())).toEqual([]);
  });

  it('drops DM (non-group) even when name in whitelist', () => {
    const r = new RoomResolver();
    r._setMap(new Map([
      [h('wxid_x'), { tableName: h('wxid_x'), username: 'wxid_x', roomName: '张三', isGroup: false }],
    ]));
    expect(r.filterWhitelistedGroupTables([h('wxid_x')], new Set(['张三']))).toEqual([]);
  });

  it('drops unknown tables silently', () => {
    const r = new RoomResolver();
    expect(r.filterWhitelistedGroupTables(['Msg_unknown'], new Set(['任意']))).toEqual([]);
  });
});

describe('RoomResolver.lookup', () => {
  it('returns undefined when not loaded', () => {
    const r = new RoomResolver();
    expect(r.lookup('Msg_xxx')).toBeUndefined();
  });
});

describe('RoomResolver contact identity', () => {
  it('resolves no-prefix self sender from chat_room owner', () => {
    const file = tempDb();
    const db = new Database(file);
    db.exec(`
      CREATE TABLE contact (username TEXT, remark TEXT, nick_name TEXT);
      CREATE TABLE chat_room (username TEXT, owner TEXT);
      INSERT INTO contact (username, remark, nick_name) VALUES ('gA@chatroom', '', '产品研发群');
      INSERT INTO contact (username, remark, nick_name) VALUES ('shin_seed', '', 'if');
      INSERT INTO chat_room (username, owner) VALUES ('gA@chatroom', 'shin_seed');
    `);
    db.close();

    const r = new RoomResolver();
    r.mergeContactNames(file);

    expect(r.resolveRoomSenderIdentity('gA@chatroom', '2')).toEqual({
      username: 'shin_seed',
      remark: null,
      nickName: 'if',
      displayName: 'if',
    });
    expect(r.resolveRoomSenderIdentity('gA@chatroom', '28')).toBeUndefined();
  });
});
