import { describe, expect, test } from 'bun:test';
import type { Capability } from './registry';
import {
  CAPABILITIES,
  CAPABILITY_BY_KEY,
  GRANTABLE_CAPABILITIES,
  capabilityForApiPath,
  capabilityForWsProvider,
  isRequestAllowedAtLevel,
  isSelfServiceRoute,
} from './registry';
import { assertCapabilityTotality, isExemptApiPath } from './totality';

// The database-backed half (authorize.ts) is exercised against the live schema; this file covers the pure
// half, which is where the rules actually live. Everything here runs without a database.

// Mirrors the `handlers` map in server.tsx by hand, which is itself the drift this file keeps catching.
// `cliamp` and `cliamp-audio` left on 2026-08-15 with `plugins/music/cliamp/` — see below.
const REAL_WS = ['terminal', 'chat', 'task-runner', 'pipeline', 'desktop', 'vault', 'sidecar'];
const realApi = () => [...new Set(CAPABILITIES.flatMap((c) => c.api))];
const surface = () => ({
  apiPrefixes: [...realApi(), '/auth', '/landing-page-data', '/waitlist', '/vault', '/sidecar'],
  wsProviders: REAL_WS,
});

describe('totality', () => {
  test('the registry covers its own declared surface', () => {
    expect(() => assertCapabilityTotality(surface())).not.toThrow();
  });

  // The four ways this is allowed to fail. Each one is a real bug it exists to catch, and a check that
  // only ever passes is worth nothing — so assert that it refuses, not merely that it runs.
  test('refuses a mounted router no capability claims', () => {
    const s = surface();
    s.apiPrefixes.push('/newthing');
    expect(() => assertCapabilityTotality(s)).toThrow(/\/api\/newthing is mounted but no capability claims it/);
  });

  test('refuses a served socket no capability claims — the 2026-08-06 hole', () => {
    const s = surface();
    s.wsProviders = [...REAL_WS, 'newsocket'];
    expect(() => assertCapabilityTotality(s)).toThrow(/websocket provider 'newsocket' is served/);
  });

  test('refuses a claim on a router that no longer exists', () => {
    const s = surface();
    s.apiPrefixes = s.apiPrefixes.filter((p) => p !== '/gitea');
    expect(() => assertCapabilityTotality(s)).toThrow(/claims \/api\/gitea, which nothing mounts/);
  });

  test('refuses a claim on a socket that is not served', () => {
    const s = surface();
    s.wsProviders = REAL_WS.filter((p) => p !== 'terminal');
    expect(() => assertCapabilityTotality(s)).toThrow(/claims websocket 'terminal', which is not served/);
  });

  test('no two capabilities claim the same prefix', () => {
    const seen = new Map<string, string>();
    for (const capability of CAPABILITIES) {
      for (const prefix of capability.api) {
        expect(seen.has(prefix)).toBe(false);
        seen.set(prefix, capability.key);
      }
    }
  });

  test('signin is exempt and gitea is not', () => {
    expect(isExemptApiPath('/api/auth/signin')).toBe(true);
    expect(isExemptApiPath('/api/gitea')).toBe(false);
    expect(isExemptApiPath('/api/dashboards/4')).toBe(false);
  });
});

describe('path → capability', () => {
  test('resolves a prefix and its descendants', () => {
    expect(capabilityForApiPath('/api/gitea')?.key).toBe('gitea');
    expect(capabilityForApiPath('/api/gitea/repos/a/b')?.key).toBe('gitea');
  });

  test('does not match a prefix that is merely a string prefix', () => {
    // '/api/username' must not resolve to the 'account' capability, which claims '/user'. A naive
    // startsWith would. (This was '/api/musicbrainz' against 'music' until music became a plugin.)
    expect(capabilityForApiPath('/api/username')).toBeNull();
  });

  test('longest prefix wins, so /dav and /caldav do not fight', () => {
    expect(capabilityForApiPath('/api/caldav/x')?.key).toBe('calendar');
    expect(capabilityForApiPath('/api/dav/x')?.key).toBe('calendar');
  });

  test('an unclaimed path resolves to nothing rather than to something permissive', () => {
    expect(capabilityForApiPath('/api/not-a-thing')).toBeNull();
  });

  test('sockets resolve to their capability', () => {
    expect(capabilityForWsProvider('terminal')?.key).toBe('terminal');
    expect(capabilityForWsProvider('chat')?.key).toBe('chat');
    expect(capabilityForWsProvider('nope')).toBeNull();
  });

  // This pinned a real hole for one day: `/api/cliamp/ws` and `/api/cliamp/audio/ws` were SERVED in
  // server.tsx's route table while no capability claimed them and their `handlers` entries were commented
  // out — so connecting crashed on a non-null assertion, and the boot check could not see any of it
  // because it reads `Object.keys(handlers)` rather than the route table.
  //
  // Closed on 2026-08-15 by cliamp leaving for `plugins/music/cliamp/`: the routes, the relay and the
  // provider names all went with it, and the two lists agree again. Kept as an assertion rather than
  // deleted, because "the route table serves nothing the handlers map lacks" is the invariant the
  // original incident was about, and this is the cheapest place to notice it breaking again.
  test('no cliamp socket is served or claimed — the route table and handlers agree', () => {
    expect(capabilityForWsProvider('cliamp')).toBeNull();
    expect(capabilityForWsProvider('cliamp-audio')).toBeNull();
    expect(REAL_WS).not.toContain('cliamp');
  });
});

describe('levels', () => {
  // A FIXTURE, not a registry entry.
  //
  // These tests ran against the real `music` capability until 2026-08-15, when music left with
  // `plugins/music/`. Re-anchoring them on whichever entry happens to have a `personal` list today only
  // moves the problem to the next extraction — and it had already half-broken before that, because the
  // moment music's `api` was commented out (2026-08-13) every path below stopped matching and three of
  // these four tests passed for the wrong reason: everything is refused when nothing is claimed.
  //
  // `isRequestAllowedAtLevel` is a pure function of a Capability. Handing it one states what is actually
  // under test — the RULE — rather than borrowing a feature that can leave.
  const fixture: Capability = {
    key: 'fixture',
    label: 'Fixture',
    description: 'Not in the registry — a shape to exercise the level rules against',
    kind: 'app',
    api: ['/fixture'],
    personal: ['/favorites', '/now-playing'],
  };

  test('write permits anything within the capability', () => {
    expect(isRequestAllowedAtLevel(fixture, 'write', 'DELETE', '/api/fixture/track/9')).toBe(true);
  });

  test('read permits safe methods', () => {
    expect(isRequestAllowedAtLevel(fixture, 'read', 'GET', '/api/fixture/albums')).toBe(true);
    expect(isRequestAllowedAtLevel(fixture, 'read', 'HEAD', '/api/fixture/albums')).toBe(true);
  });

  test('read permits mutations only under personal sub-paths', () => {
    expect(isRequestAllowedAtLevel(fixture, 'read', 'POST', '/api/fixture/favorites/7')).toBe(true);
    expect(isRequestAllowedAtLevel(fixture, 'read', 'PUT', '/api/fixture/now-playing')).toBe(true);
    expect(isRequestAllowedAtLevel(fixture, 'read', 'POST', '/api/fixture/scan')).toBe(false);
    expect(isRequestAllowedAtLevel(fixture, 'read', 'DELETE', '/api/fixture/track/9')).toBe(false);
  });

  test('a personal entry does not leak across a name boundary', () => {
    // '/favorites-export' must not be covered by the '/favorites' personal entry.
    expect(isRequestAllowedAtLevel(fixture, 'read', 'POST', '/api/fixture/favorites-export')).toBe(false);
  });

  test('a plugin gets the same rule through readOnlyWrites', () => {
    // The two lists are concatenated, so a plugin declaring per-caller paths on the one field its
    // manifest has behaves identically to a core capability declaring `personal`. This is what music
    // relies on now that it ships as one.
    const plugin: Capability = { ...fixture, personal: undefined, readOnlyWrites: ['/favorites', '/now-playing'] };
    expect(isRequestAllowedAtLevel(plugin, 'read', 'POST', '/api/fixture/favorites/7')).toBe(true);
    expect(isRequestAllowedAtLevel(plugin, 'read', 'POST', '/api/fixture/scan')).toBe(false);
  });
});

describe('self-service routes', () => {
  const userAdmin = CAPABILITY_BY_KEY.get('user-admin')!;

  test('PUT /api/users is self-profile update and stays reachable', () => {
    expect(isSelfServiceRoute(userAdmin, 'PUT', '/api/users')).toBe(true);
    expect(isSelfServiceRoute(userAdmin, 'put', '/api/users')).toBe(true);
  });

  test('it does not open the rest of the router', () => {
    expect(isSelfServiceRoute(userAdmin, 'GET', '/api/users')).toBe(false);
    expect(isSelfServiceRoute(userAdmin, 'DELETE', '/api/users/5')).toBe(false);
    expect(isSelfServiceRoute(userAdmin, 'PATCH', '/api/users/5/role')).toBe(false);
    // The exact-match rule: a descendant of a self-service path is not self-service.
    expect(isSelfServiceRoute(userAdmin, 'PUT', '/api/users/5')).toBe(false);
  });

  test('capabilities without the field are unaffected', () => {
    expect(isSelfServiceRoute(CAPABILITY_BY_KEY.get('wallet')!, 'PUT', '/api/wallet')).toBe(false);
  });
});

describe('kinds', () => {
  test('execution capabilities are never grantable', () => {
    const grantable = new Set(GRANTABLE_CAPABILITIES.map((c) => c.key));
    // `files` left this list on 2026-08-11, then `terminal` and `chat` the same day — see the tests below and
    // docs/per-user-linux-accounts.md. Everything still here runs as the OWNER in the owner's home with no
    // per-caller resolution at all.
    for (const key of ['tasks', 'desktop', 'browser', 'items']) {
      expect(CAPABILITY_BY_KEY.get(key)?.kind).toBe('execution');
      expect(grantable.has(key)).toBe(false);
    }
  });

  // A confined capability is grantable, but the grant is inert without a Linux account — enforced in
  // authorize.ts, which is where the rule can cover routes, sockets and the dock at once.
  test('confined capabilities are grantable', () => {
    const grantable = new Set(GRANTABLE_CAPABILITIES.map((c) => c.key));
    for (const key of ['files', 'terminal', 'chat']) {
      expect(CAPABILITY_BY_KEY.get(key)?.kind).toBe('confined');
      expect(grantable.has(key)).toBe(true);
    }
  });

  // The claim `confined` makes is that every path it reaches resolves its directory from the CALLER. That
  // cannot be asserted from the registry, so this pins the inverse: nothing becomes confined without a
  // deliberate edit here, and the list stays short enough to audit by eye.
  //
  // `chat` was on this list ahead of its implementation for a day, with `api/chat/chat.ts` and the chat socket
  // both refusing non-owners because a turn still spawned the agent as the owner. Both refusals were removed
  // on 2026-08-12, together, once the turn ran under `runAs` with the member's own home, credential,
  // transcripts and session ownership. `chat` is now confined in fact and not only in the registry.
  test('confined is a short, deliberate list', () => {
    expect(CAPABILITIES.filter((c) => c.kind === 'confined').map((c) => c.key)).toEqual(['terminal', 'chat', 'files']);
  });

  test('admin capabilities are never grantable', () => {
    const grantable = new Set(GRANTABLE_CAPABILITIES.map((c) => c.key));
    // `headscale` was here until 2026-08-15, when it left with offscale. A plugin's permissions are
    // registered at install from its manifest, so they are not in this compile-time list by design.
    for (const key of ['user-admin', 'server-admin', 'wallet']) {
      expect(CAPABILITY_BY_KEY.get(key)?.kind).toBe('admin');
      expect(grantable.has(key)).toBe(false);
    }
  });

  test('gitea is grantable — the case this was built for', () => {
    expect(GRANTABLE_CAPABILITIES.some((c) => c.key === 'gitea')).toBe(true);
  });

  test('every capability declares at least one api prefix', () => {
    for (const capability of CAPABILITIES) expect(capability.api.length).toBeGreaterThan(0);
  });
});
