import { AccessRule, type AccessRuleSchema } from './AccessRule.js'
import { observed } from '../../decorators/observed.js'

/**
 * The action is allowed if a specific property on the authenticated user matches an expected value.
 * This is used to enforce other user-specific restrictions.
 */
export interface MatchUserPropertyAccessRuleSchema extends AccessRuleSchema {
  type: 'matchUserProperty'
  /**
   * The property on the authenticated user that should match the expected value.
   */
  property: string
  /**
   * The expected value for the user property.
   */
  value: string
}

/**
 * The action is allowed if a specific property on the authenticated user matches an expected value.
 * This is used to enforce other user-specific restrictions.
 */
export class MatchUserPropertyAccessRule extends AccessRule implements MatchUserPropertyAccessRuleSchema {
  override readonly type: 'matchUserProperty'

  @observed() accessor property: string
  @observed() accessor value: string

  constructor(state: Partial<MatchUserPropertyAccessRuleSchema> = {}) {
    super(state)
    this.type = 'matchUserProperty'
    this.property = state.property ?? ''
    this.value = state.value ?? ''
  }

  override toJSON(): MatchUserPropertyAccessRuleSchema {
    return {
      ...(super.toJSON() as MatchUserPropertyAccessRuleSchema),
      property: this.property,
      value: this.value,
    }
  }
}
