import type {
  AccessRule,
  AllowAuthenticatedAccessRule,
  AllowPublicAccessRule,
  MatchEmailDomainAccessRule,
  MatchResourceOwnerAccessRule,
  MatchUserPropertyAccessRule,
  MatchUserRoleAccessRule,
} from '@api-client/core/browser.js'

function createPublicRule(): AllowPublicAccessRule {
  return { type: 'public' } as AllowPublicAccessRule
}

function createAuthenticatedRule(): AllowAuthenticatedAccessRule {
  return { type: 'authenticated' } as AllowAuthenticatedAccessRule
}

function createResourceOwnerRule(): MatchResourceOwnerAccessRule {
  return { type: 'resourceOwner', property: '' } as MatchResourceOwnerAccessRule
}

function createMatchUserRoleRule(): MatchUserRoleAccessRule {
  return { type: 'matchUserRole', role: [] } as MatchUserRoleAccessRule
}

function createMatchUserPropertyRule(): MatchUserPropertyAccessRule {
  return { type: 'matchUserProperty', property: '', value: '' } as MatchUserPropertyAccessRule
}

function createMatchEmailDomainRule(): MatchEmailDomainAccessRule {
  return { type: 'matchEmailDomain', domains: [] } as MatchEmailDomainAccessRule
}

/**
 * Creates an empty access rule of the given type.
 * @param rule The rule to create.
 * @returns The new and empty rule.
 */
export function createEmptyAccessRule(rule: AccessRule['type']): AccessRule {
  switch (rule) {
    case 'public':
      return createPublicRule()
    case 'authenticated':
      return createAuthenticatedRule()
    case 'resourceOwner':
      return createResourceOwnerRule()
    case 'matchUserRole':
      return createMatchUserRoleRule()
    case 'matchUserProperty':
      return createMatchUserPropertyRule()
    case 'matchEmailDomain':
      return createMatchEmailDomainRule()
    default:
      throw new Error(`Cannot create access rule of unknown type: ${rule}`)
  }
}
