import { describe, expect, it } from 'vitest'

import { AccessKeys } from '../access-keys'
import { checkAccess, createAccessModel, type AccessContext } from '../access-model'
import { accessTestOrganizationModel } from './access-test-fixtures'

const bypassAnswer = {
  allowed: true,
  restrictedBy: null,
  reason: 'platform-admin-bypass'
} as const

const baseContext: AccessContext = {
  organizationId: 'org-1',
  organizationModel: accessTestOrganizationModel,
  membership: {
    id: 'membership-1',
    organizationId: 'org-1',
    effectivePermissions: []
  },
  profile: {
    id: 'user-1',
    isPlatformAdmin: false
  }
}

describe('platform admin bypass parity', () => {
  it('short-circuits unknown keys before catalog and membership checks', () => {
    expect(
      checkAccess('unknown.system', {
        ...baseContext,
        membership: null,
        profile: { id: 'admin', isPlatformAdmin: true }
      })
    ).toEqual(bypassAnswer)
  })

  it('supports both camelCase and database-shaped platform-admin profile flags', () => {
    expect(
      checkAccess('unknown.system', {
        ...baseContext,
        membership: null,
        profile: { id: 'admin', is_platform_admin: true }
      })
    ).toEqual(bypassAnswer)
  })

  it('returns the same bypass answer through createAccessModel', () => {
    const accessModel = createAccessModel(accessTestOrganizationModel)

    expect(
      accessModel.checkAccess('unknown.system', {
        ...baseContext,
        membership: null,
        profile: { id: 'admin', isPlatformAdmin: true }
      })
    ).toEqual(bypassAnswer)
  })

  it('does not grant platformAdmin access to non-platform admins', () => {
    expect(checkAccess(AccessKeys.platformAdmin, baseContext)).toEqual({
      allowed: false,
      restrictedBy: 'role-permission',
      reason: 'role-permission-denied'
    })
  })
})
