import type { EffectiveUser } from './effective-user'

/**
 * Who can mark entries as transferred / un-transfer batches.
 * Currently: org owner OR super admin (when not viewing-as a non-owner).
 */
export function canTransfer(eu: EffectiveUser | null): boolean {
  if (!eu) return false
  if (eu.is_super_admin && !eu.is_viewing_as) return true
  return eu.org_role === 'owner'
}

/**
 * Who can manage the team list (add/edit/delete team members).
 * Owners and managers; anyone with org-level write access.
 */
export function canManageTeam(eu: EffectiveUser | null): boolean {
  if (!eu) return false
  if (eu.is_super_admin && !eu.is_viewing_as) return true
  return eu.org_role === 'owner' || eu.org_role === 'manager'
}

/**
 * Who can upload Clockify CSVs / delete batches.
 */
export function canManageImports(eu: EffectiveUser | null): boolean {
  if (!eu) return false
  if (eu.is_super_admin && !eu.is_viewing_as) return true
  return eu.org_role === 'owner' || eu.org_role === 'manager'
}

/**
 * Who can switch into view-as mode. Only super admins, and only
 * when not already viewing-as (no nesting).
 */
export function canEnterViewAs(eu: EffectiveUser | null): boolean {
  if (!eu) return false
  return eu.is_super_admin && !eu.is_viewing_as
}

/**
 * Per-entry edit permission. Once an entry is attached to an invoice
 * (or, for legacy rows, marked transferred) it's locked — only owners
 * can edit or delete it. Detaching from the invoice unlocks it for
 * everyone with manage-imports permission again.
 *
 * The transferred_at branch is kept for safety — after the
 * transfer→invoice migration every transferred entry also has an
 * invoice_id, but if something slipped through we still honor the old
 * lock until it's repaired.
 */
export function canEditEntry(
  eu: EffectiveUser | null,
  entry: { invoice_id?: string | null; transferred_at?: string | null },
): boolean {
  if (!eu) return false
  if (entry.invoice_id || entry.transferred_at) return canTransfer(eu)
  return canManageImports(eu)
}
