/**
 * Global mcpd settings, stored as JSON in a well-known Secret's `data` field.
 *
 * We deliberately reuse the Secret object instead of adding schema columns:
 * Secrets already have CRUD, RBAC, and backup/restore, so settings stay
 * admin-editable through the same tooling with no migration per flag.
 * See the `backup-ssh` secret for the original precedent.
 */

import type { PrismaClient } from '@prisma/client';

/** Well-known secret holding global mcpd settings as `data` JSON. */
export const SYSTEM_SETTINGS_SECRET = 'mcpctl-system-settings';

/** Settings key: whether newly-created users get self password-change permission. */
export const SETTING_ALLOW_SELF_PASSWORD = 'allowSelfPasswordChange';

/** Coerce a stored JSON value (boolean, or "true"/"false"/"0" string) to boolean. */
function toBool(v: unknown, dflt: boolean): boolean {
  if (typeof v === 'boolean') return v;
  if (typeof v === 'string') {
    const s = v.trim().toLowerCase();
    if (s === 'false' || s === '0' || s === '') return false;
    return true;
  }
  return dflt;
}

/**
 * Whether new users should receive the `set-own-password` permission by default.
 *
 * Defaults to TRUE — a fresh install allows self-service password changes.
 * An admin disables it by setting `allowSelfPasswordChange: false` in the
 * `mcpctl-system-settings` secret. Missing secret / missing key / read error
 * all fall back to the permissive default.
 */
export async function getAllowSelfPasswordChange(prisma: PrismaClient): Promise<boolean> {
  try {
    const secret = await prisma.secret.findUnique({ where: { name: SYSTEM_SETTINGS_SECRET } });
    if (!secret) return true;
    const data = (secret.data ?? {}) as Record<string, unknown>;
    if (!(SETTING_ALLOW_SELF_PASSWORD in data)) return true;
    return toBool(data[SETTING_ALLOW_SELF_PASSWORD], true);
  } catch {
    return true;
  }
}
