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

/**
 * The action is allowed if the authenticated user's email domain matches a specific domain.
 * This is used to restrict access based on the user's email address.
 * For example, only users with an email address from "my-company.com" can access certain resources.
 */
export interface MatchEmailDomainAccessRuleSchema extends AccessRuleSchema {
  type: 'matchEmailDomain'
  /**
   * The email domains that the authenticated user's email must match.
   */
  domains: string[]
}

/**
 * The action is allowed if the authenticated user's email domain matches a specific domain.
 * This is used to restrict access based on the user's email address.
 * For example, only users with an email address from "my-company.com" can access certain resources.
 */
export class MatchEmailDomainAccessRule extends AccessRule implements MatchEmailDomainAccessRuleSchema {
  override readonly type: 'matchEmailDomain'

  @observed({ deep: true }) accessor domains: string[]

  constructor(state: Partial<MatchEmailDomainAccessRuleSchema> = {}) {
    super(state)
    this.type = 'matchEmailDomain'
    this.domains = state.domains ? [...state.domains] : []
  }

  override toJSON(): MatchEmailDomainAccessRuleSchema {
    return {
      ...(super.toJSON() as MatchEmailDomainAccessRuleSchema),
      domains: structuredClone(toRaw(this, this.domains)) as string[],
    }
  }
}
