import { CommentAuthzError } from './errors.js'
import type { Actor, CommentAuthor } from './types.js'

/**
 * Object-level authz — IDOR floor (spec §3).
 * Allowed: authoring user OR actor.canModerate.
 * Guest-authored comments: no session identity → only a moderator may modify (standard comment behavior).
 */
export function assertCanModify(
  actor: Actor | null,
  action: string,
  owner: CommentAuthor,
  commentId: string,
): void {
  if (actor?.canModerate) return

  if (owner.kind === 'guest') {
    // Guest-authored: no identity to compare — only moderator path (already handled above)
    throw new CommentAuthzError(action, actor?.id ?? null, commentId, 'guest-authored comment requires moderator to modify')
  }

  if (owner.kind === 'user') {
    if (actor?.id === owner.userId) return
    throw new CommentAuthzError(action, actor?.id ?? null, commentId, 'actor is not the author and lacks canModerate')
  }

  throw new CommentAuthzError(action, actor?.id ?? null, commentId, 'unknown author kind')
}

/**
 * Moderation transition gate (spec §3).
 * setStatus requires canModerate.
 */
export function assertCanModerate(actor: Actor, action: string, commentId: string): void {
  if (!actor.canModerate) {
    throw new CommentAuthzError(action, actor.id, commentId, 'actor lacks canModerate')
  }
}
