import { readFileSync } from 'node:fs';
import { dirname, join } from 'node:path';
import { fileURLToPath } from 'node:url';
import { PlatformError } from '../../kernel/errors.mjs';

const here = dirname(fileURLToPath(import.meta.url));
const manifest = JSON.parse(readFileSync(join(here, 'module.json'), 'utf8'));
let service = null;
let setupTokenMatcher = () => false;

export function configureAuthModule({ setupTokenMatches }) {
  if (typeof setupTokenMatches === 'function') setupTokenMatcher = setupTokenMatches;
}

export function getAuthService() {
  if (!service) throw new PlatformError('Auth-Modul ist noch nicht gestartet.', { code: 'AUTH_MODULE_NOT_READY', status: 503, expose: true });
  return service;
}

export function createAuthModule() {
  return {
    manifest,
    lifecycle: {
      async start() {
        const { createAuthService } = await import('./service.mjs');
        service = createAuthService({ setupTokenMatches: setupTokenMatcher });
      },
      async stop() { service = null; },
      async health() { return getAuthService().health(); },
    },
  };
}
