import {
  cleanExpiredSessions, destroyOwnedSessionById, destroySessionById, destroyUserSessions,
  getAllActiveSessions, getSessionById, getUserSessions,
} from '../../core/identity/identity-store.mjs';
import { PlatformError } from '../../kernel/errors.mjs';

function fail(message, status = 400, code = 'SESSION_OPERATION_FAILED') {
  throw new PlatformError(message, { status, code, expose: true });
}

export function createSessionsService() {
  return Object.freeze({
    listAll() { return getAllActiveSessions(); },
    listForUser(userId) { return getUserSessions(userId); },
    revokeAsAdmin(sessionId) {
      const session = getSessionById(sessionId);
      if (!session) fail('Sitzung nicht gefunden.', 404, 'SESSION_NOT_FOUND');
      destroySessionById(sessionId);
      return session;
    },
    revokeAllForUser(userId) {
      destroyUserSessions(userId);
      return { user_id: Number(userId) };
    },
    revokeOwn(userId, sessionId) {
      const changed = destroyOwnedSessionById(userId, sessionId);
      if (!changed) fail('Sitzung nicht gefunden oder gehört nicht zu diesem Benutzer.', 404, 'SESSION_NOT_OWNED');
      return { id: Number(sessionId), user_id: Number(userId) };
    },
    cleanup() { cleanExpiredSessions(); return { ok: true }; },
    health() { return { ok: true, active_sessions: getAllActiveSessions().length }; },
  });
}
