import { readFileSync } from 'node:fs';
import { dirname, join, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import { objectSchema } from '../app/kernel/input-schema.mjs';

const root = resolve(dirname(fileURLToPath(import.meta.url)), '..');
const read = rel => readFileSync(join(root, rel), 'utf8');
const failures = [];
const assert = (condition, message) => { if (!condition) failures.push(message); };
const expectThrow = (fn, message) => { try { fn(); failures.push(message); } catch {} };

const pkg = JSON.parse(read('package.json'));
assert(pkg.version === '1.38.0', `Paketversion ist ${pkg.version}`);
const server = read('server.mjs');
const authFacade = read('lib/auth.mjs');
const identityStore = read('app/core/identity/identity-store.mjs');
const authRoutes = read('app/modules/auth/routes.mjs');
const userRoutes = read('app/modules/users/routes.mjs');
const userService = read('app/modules/users/service.mjs');
const sessionRoutes = read('app/modules/sessions/routes.mjs');
const sessionService = read('app/modules/sessions/service.mjs');
const settingsService = read('app/modules/settings/service.mjs');
const settingsRoutes = read('app/modules/settings/routes.mjs');

assert(authFacade.includes("export * from '../app/core/identity/identity-store.mjs'"), 'lib/auth.mjs ist kein reiner Kompatibilitäts-Facade');
for (const marker of ['destroyOwnedSessionById', 'AND user_id = ?', 'getSessionById', 'last_seen_at']) assert(identityStore.includes(marker), `Identity-Store fehlt: ${marker}`);
for (const marker of ['registerPublicAuthRoutes', 'registerUsersRoutes', 'registerSessionRoutes', 'registerSettingsRoutes']) assert(server.includes(marker), `Server registriert native Route nicht: ${marker}`);
for (const legacy of ["app.get('/auth/setup-check'", "app.post('/auth/login'", "app.get('/api/admin/users'", "app.get('/api/admin/sessions'", "app.get('/api/settings'", "app.get('/api/admin/smtp'"]) assert(!server.includes(legacy), `Legacy-Route verblieben: ${legacy}`);

for (const marker of ["policy: 'auth.public'", "policy: 'auth.authenticated'", 'objectSchema', 'setSessionCookies']) assert(authRoutes.includes(marker), `Auth-Routenvertrag fehlt: ${marker}`);
for (const marker of ["policy: 'users.manage'", 'Der letzte aktive Administrator', 'users.admin.password-reset']) assert((userRoutes + userService).includes(marker), `Benutzer-Schutz fehlt: ${marker}`);
for (const marker of ["policy: 'sessions.self'", 'revokeOwn', 'SESSION_NOT_OWNED']) assert((sessionRoutes + sessionService).includes(marker), `Sitzungs-Eigentümerschutz fehlt: ${marker}`);
for (const marker of ['ALL_FIELDS', 'Unbekanntes Einstellungsfeld', 'SECRET_FIELDS', 'RUNTIME_FIELDS', "policy: 'settings.manage'"]) assert((settingsService + settingsRoutes).includes(marker), `Settings-Allowlist fehlt: ${marker}`);

const schema = objectSchema({ role: { type:'string', enum:['admin','viewer'] }, id: { type:'integer', min:1 } });
const valid = schema({ role:'admin', id:2 });
assert(valid.role === 'admin' && valid.id === 2, 'Enum-/Integer-Schema validiert gültige Werte nicht');
expectThrow(() => schema({ role:'owner', id:2 }), 'Unbekannte Rolle wurde akzeptiert');
expectThrow(() => schema({ role:'admin', id:1.5 }), 'Nicht-ganzzahlige ID wurde akzeptiert');
expectThrow(() => schema({ role:'admin', id:2, extra:true }), 'Unbekanntes Feld wurde akzeptiert');

for (const [id, expected] of [['auth','native'],['users','native'],['sessions','native'],['settings','native']]) {
  const manifest = JSON.parse(read(`app/modules/${id}/module.json`));
  assert(manifest.status === expected, `${id}-Modul ist nicht nativ`);
}

if (failures.length) { console.error(`Identity-&-Settings-Gate 1.38.0 fehlgeschlagen (${failures.length}):`); failures.forEach(item => console.error(`- ${item}`)); process.exit(1); }
console.log('Identity-&-Settings-Gate 1.38.0 erfolgreich: native Auth-, Benutzer-, Sitzungs- und Settings-Routen, letzten-Admin-Schutz, Sitzungs-Eigentümerprüfung und Settings-Allowlist geprüft.');
