import type { Consultant, Assignment } from './planning-types'

export type PlanningRole = 'masteradmin' | 'admin' | 'team_lead' | 'consultant' | 'readonly'

// Serializable — safe to pass as Next.js server → client props
export interface PlanningPerms {
  role: PlanningRole
  consultantId: string | null
  teamCode: string | null
  canCreate: boolean
  canManageMasterData: boolean
  canViewReports: boolean
}

// Authoritative auth role — comes from user_profiles + roles, not from the
// planning-module consultants table. We pass it explicitly so the planning
// module can recognise an admin/masteradmin who is NOT also listed in
// consultants (which used to be the failure mode that hid the create button
// from anyone without a consultant record).
export type AuthRole = 'masteradmin' | 'admin' | 'consultant' | 'readonly' | string

const AUTH_ESCALATION_ROLES: ReadonlySet<string> = new Set(['masteradmin', 'admin'])

export function getPlanningPerms(
  currentConsultant: Consultant | null,
  authRole: AuthRole | null = null,
): PlanningPerms {
  const consultantRole = (currentConsultant?.role as PlanningRole | undefined) ?? null
  const authRoleEscalates = !!authRole && AUTH_ESCALATION_ROLES.has(authRole)

  // If the auth role escalates (admin/masteradmin), it wins over a missing or
  // lower consultant role. Otherwise fall back to the consultant role; if
  // neither is present, default to readonly.
  let role: PlanningRole
  if (authRoleEscalates) {
    role = (authRole as PlanningRole)
  } else if (consultantRole) {
    role = consultantRole
  } else {
    role = 'readonly'
  }

  return {
    role,
    consultantId:        currentConsultant?.id         ?? null,
    teamCode:            currentConsultant?.team_code  ?? null,
    canCreate:           role !== 'readonly',
    canManageMasterData: role === 'admin' || role === 'masteradmin',
    canViewReports:      role !== 'readonly',
  }
}

// Per-assignment checks — call these client-side, they are NOT part of the serialized perms
export function canEditAssignment(perms: PlanningPerms, a: Assignment): boolean {
  if (perms.role === 'masteradmin' || perms.role === 'admin' || perms.role === 'team_lead') return true
  if (perms.role === 'consultant') return a.consultant_id === perms.consultantId
  return false
}

export function canDeleteAssignment(perms: PlanningPerms, a: Assignment): boolean {
  if (perms.role === 'masteradmin' || perms.role === 'admin' || perms.role === 'team_lead') return true
  if (perms.role === 'consultant') return a.consultant_id === perms.consultantId
  return false
}
