import { describe, it, expect } from 'vitest'
import { Users } from '@/collections/Users'

const updateAccess = Users.access?.update

describe('Users collection access controls', () => {
  it('allows super admins to update any account', async () => {
    expect(updateAccess).toBeTypeOf('function')

    const result = await (updateAccess as any)({
      req: { user: { id: 1, isSuperAdmin: true } },
      id: 999,
    })

    expect(result).toBe(true)
  })

  it('allows users to update their own account only', async () => {
    const ownResult = await (updateAccess as any)({
      req: { user: { id: 42, isSuperAdmin: false } },
      id: 42,
    })
    const foreignResult = await (updateAccess as any)({
      req: { user: { id: 42, isSuperAdmin: false } },
      id: 99,
    })

    expect(ownResult).toBe(true)
    expect(foreignResult).toBe(false)
  })

  it('denies anonymous updates', async () => {
    const result = await (updateAccess as any)({
      req: { user: null },
      id: 1,
    })

    expect(result).toBe(false)
  })

  it('restricts isSuperAdmin field read/create/update to super admins', async () => {
    const superAdminField = Users.fields.find(
      (field) => 'name' in field && field.name === 'isSuperAdmin',
    ) as any

    expect(superAdminField).toBeDefined()
    expect(superAdminField.access).toBeDefined()

    const superAdminReq = { req: { user: { id: 1, isSuperAdmin: true } } }
    const regularReq = { req: { user: { id: 2, isSuperAdmin: false } } }

    expect(await superAdminField.access.read(superAdminReq)).toBe(true)
    expect(await superAdminField.access.create(superAdminReq)).toBe(true)
    expect(await superAdminField.access.update(superAdminReq)).toBe(true)

    expect(await superAdminField.access.read(regularReq)).toBe(false)
    expect(await superAdminField.access.create(regularReq)).toBe(false)
    expect(await superAdminField.access.update(regularReq)).toBe(false)
  })
})

