import { adminUserId, makeUser, load } from './setup.mjs';
import test from 'node:test';
import assert from 'node:assert/strict';

const { createHost, listHosts, updateHost, deleteHost, filterVisibleHostIds } = await load('../models/hostModel.js');

const owner = adminUserId();
const other = makeUser({ email: 'other-host@test.local' });

test('personal hosts are visible only to their owner', () => {
  const host = createHost({ name: 'Private', address: 'priv.local', osFamily: 'windows', transport: 'winrm', tags: [], visibility: 'personal' }, owner);
  assert.ok(listHosts(owner).some((h) => h.id === host.id));
  assert.ok(!listHosts(other).some((h) => h.id === host.id));
});

test('shared hosts are visible to everyone', () => {
  const host = createHost({ name: 'Shared', address: 'shared.local', osFamily: 'windows', transport: 'winrm', tags: [], visibility: 'shared' }, owner);
  assert.ok(listHosts(other).some((h) => h.id === host.id));
});

test('a non-owner cannot update or delete a personal host', () => {
  const host = createHost({ name: 'Locked', address: 'locked.local', osFamily: 'windows', transport: 'winrm', tags: [], visibility: 'personal' }, owner);
  assert.equal(updateHost(host.id, { name: 'Hacked' }, other), null);
  deleteHost(host.id, other);
  assert.ok(listHosts(owner).some((h) => h.id === host.id), 'host should still exist after foreign delete attempt');
});

test('filterVisibleHostIds drops hosts the user cannot see', () => {
  const priv = createHost({ name: 'OwnerOnly', address: 'owneronly.local', osFamily: 'windows', transport: 'winrm', tags: [], visibility: 'personal' }, owner);
  const shared = createHost({ name: 'Everyone', address: 'everyone.local', osFamily: 'windows', transport: 'winrm', tags: [], visibility: 'shared' }, owner);
  const visibleToOther = filterVisibleHostIds([priv.id, shared.id], other);
  assert.deepEqual(visibleToOther, [shared.id]);
});
