import { describe, expect, it } from 'vitest'
import { assertCanManageTaxonomy, assertCanModify, assertCanPublish, ContentAuthzError } from './authz.js'

describe('content authz', () => {
  it('lets the author modify their own entry', () => {
    expect(() => assertCanModify({ id: 'u1' }, 'update', 'u1', 'e1')).not.toThrow()
  })

  it("lets canEditAny modify someone else's entry", () => {
    expect(() => assertCanModify({ id: 'u2', canEditAny: true }, 'update', 'u1', 'e1')).not.toThrow()
  })

  it('blocks a non-author without canEditAny, carrying action + actor + entry', () => {
    try {
      assertCanModify({ id: 'u2' }, 'remove', 'u1', 'e1')
      throw new Error('expected throw')
    } catch (e) {
      expect(e).toBeInstanceOf(ContentAuthzError)
      const err = e as ContentAuthzError
      expect(err.action).toBe('remove')
      expect(err.actorId).toBe('u2')
      expect(err.entryId).toBe('e1')
    }
  })

  it('gates state transitions on canPublish', () => {
    expect(() => assertCanPublish({ id: 'u1', canPublish: true }, 'publish', 'e1')).not.toThrow()
    expect(() => assertCanPublish({ id: 'u1' }, 'publish', 'e1')).toThrow(ContentAuthzError)
  })

  it('gates taxonomy management on canManageTaxonomy', () => {
    expect(() => assertCanManageTaxonomy({ id: 'u1', canManageTaxonomy: true })).not.toThrow()
    expect(() => assertCanManageTaxonomy({ id: 'u1' })).toThrow(ContentAuthzError)
  })
})
