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

const { createScript, cloneScript, scriptUsage } = await load('../models/libraryModel.js');
const { createRunPlan } = await load('../models/runPlanModel.js');
const { createIntuneDeployment } = await load('../models/psadtModel.js');

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

test('scriptUsage reports linked RunPlans and Intune deployments', () => {
  const script = createScript({
    name: 'Usage Target.ps1',
    description: 'Used by operational plans',
    content: 'Write-Output usage',
    visibility: 'personal'
  }, owner);

  const runplan = createRunPlan({
    name: 'Usage RunPlan',
    description: '',
    scriptId: script.id,
    visibility: 'personal',
    parallel: true,
    hostIds: []
  }, owner);

  const deployment = createIntuneDeployment({
    name: 'Usage Intune Plan',
    scriptId: script.id,
    installCommand: 'Invoke-AppDeployToolkit.exe -DeploymentType Install',
    uninstallCommand: 'Invoke-AppDeployToolkit.exe -DeploymentType Uninstall',
    visibility: 'personal'
  }, owner);

  const usage = scriptUsage(script.id, owner);
  assert.equal(usage.total, 2);
  assert.deepEqual(usage.runplans.map((item) => item.id), [runplan.id]);
  assert.deepEqual(usage.intuneDeployments.map((item) => item.id), [deployment.id]);
});

test('cloneScript creates an independent unassigned script copy', () => {
  const script = createScript({
    name: 'Clone Source.ps1',
    description: 'Original',
    content: 'Write-Output clone',
    visibility: 'personal'
  }, owner);

  createRunPlan({
    name: 'Original Only',
    description: '',
    scriptId: script.id,
    visibility: 'personal',
    parallel: true,
    hostIds: []
  }, owner);

  const clone = cloneScript(script.id, { name: 'Clone Target.ps1' }, owner);
  assert.notEqual(clone.id, script.id);
  assert.equal(clone.name, 'Clone Target.ps1');
  assert.equal(clone.content, script.content);
  assert.equal(scriptUsage(clone.id, owner).total, 0);
  assert.equal(scriptUsage(script.id, owner).total, 1);
});
