import { describe, it, expect } from 'vitest';

import { NotFoundError } from '@/lib/errors';
import {
  assertResidentialModuleEnabled,
  disableResidentialModule,
  enableResidentialModule,
  isResidentialModuleEnabled,
} from '@/lib/services/residential-module.service';
import { makePort } from '../helpers/factories';

describe('residential module gate', () => {
  it('defaults to ENABLED for a fresh port (no setting row)', async () => {
    const port = await makePort();
    expect(await isResidentialModuleEnabled(port.id)).toBe(true);
  });

  it('disableResidentialModule turns it off (soft hide; setting persists)', async () => {
    const port = await makePort();
    await disableResidentialModule(port.id);
    expect(await isResidentialModuleEnabled(port.id)).toBe(false);
  });

  it('enableResidentialModule turns it back on after a disable', async () => {
    const port = await makePort();
    await disableResidentialModule(port.id);
    expect(await isResidentialModuleEnabled(port.id)).toBe(false);
    await enableResidentialModule(port.id);
    expect(await isResidentialModuleEnabled(port.id)).toBe(true);
  });

  it('enable/disable are idempotent (safe to call when already in that state)', async () => {
    const port = await makePort();
    await enableResidentialModule(port.id);
    await enableResidentialModule(port.id);
    expect(await isResidentialModuleEnabled(port.id)).toBe(true);
    await disableResidentialModule(port.id);
    await disableResidentialModule(port.id);
    expect(await isResidentialModuleEnabled(port.id)).toBe(false);
  });

  it('assertResidentialModuleEnabled resolves when enabled', async () => {
    const port = await makePort();
    await expect(assertResidentialModuleEnabled(port.id)).resolves.toBeUndefined();
  });

  it('assertResidentialModuleEnabled throws NotFoundError when disabled', async () => {
    const port = await makePort();
    await disableResidentialModule(port.id);
    await expect(assertResidentialModuleEnabled(port.id)).rejects.toBeInstanceOf(NotFoundError);
  });
});
