/**
 * TwoFactorPolicy Model
 *
 * A company-scoped two-factor policy, set by an org admin for the users they
 * manage.
 *
 * `scope` follows the convention `Role` already uses in this codebase —
 * `'global'` for platform-wide, a `companyId` for org-scoped — so precedence is
 * expressed the same way everywhere rather than as a second parallel concept.
 *
 * In practice only company-scoped documents are written here: the global policy
 * continues to live on `superAdmin.panelSettings.twoFactor`, which is where it
 * already worked, so nothing on the authentication path had to be migrated. The
 * `'global'` value stays legal so that source can move later without a schema
 * change.
 *
 * An org policy is a *floor raise*, never a relaxation — see `combinePolicies`
 * in services/auth/policyResolution.ts. What is stored here is the admin's
 * requested policy; what a user actually gets is that combined with the global
 * one.
 */

import mongoose, { Schema, Document, Types } from 'mongoose';

export interface ITwoFactorPolicy extends Document {
  /** `'global'` or a companyId — same convention as `Role.scope`. */
  scope: string;
  /** The requested policy, in the same shape as the global settings blob. */
  settings: Record<string, any>;
  updatedByUserId?: Types.ObjectId;
  createdAt: Date;
  updatedAt: Date;
}

const TwoFactorPolicySchema = new Schema<ITwoFactorPolicy>({
  scope: {
    type: String,
    required: true,
    unique: true,
    index: true,
    trim: true,
  },
  settings: {
    type: Schema.Types.Mixed,
    default: {},
  },
  updatedByUserId: {
    type: Schema.Types.ObjectId,
    ref: 'User',
  },
}, {
  timestamps: true,
});

// One policy per scope — a company having two would make "the" org policy
// ambiguous and the resolver non-deterministic.
TwoFactorPolicySchema.index({ scope: 1 }, { unique: true });

export const TwoFactorPolicy =
  mongoose.models.TwoFactorPolicy ||
  mongoose.model<ITwoFactorPolicy>('TwoFactorPolicy', TwoFactorPolicySchema);
