import type { User, Tenant } from '../payload-types'
import { extractID } from '../utilities/extractID'

/**
 * Tenant role types for care home staff
 */
export type TenantRole = 'admin' | 'caregiver' | 'kitchen'

/**
 * Check if user has a specific tenant role in any tenant
 */
export const hasTenantRole = (user: User | null | undefined, role: TenantRole): boolean => {
  if (!user?.tenants) return false
  return user.tenants.some((t) => t.roles?.includes(role))
}

/**
 * Check if user has a specific tenant role in a specific tenant
 */
export const hasTenantRoleInTenant = (
  user: User | null | undefined,
  role: TenantRole,
  tenantId: number | string,
): boolean => {
  if (!user?.tenants) return false
  const targetId = String(tenantId)
  return user.tenants.some(
    (t) => String(extractID(t.tenant)) === targetId && t.roles?.includes(role),
  )
}

/**
 * Get tenant IDs where user has a specific role
 */
export const getTenantIDsWithRole = (
  user: User | null | undefined,
  role: TenantRole,
): Tenant['id'][] => {
  if (!user?.tenants) return []
  return user.tenants
    .filter((t) => t.roles?.includes(role))
    .map((t) => extractID(t.tenant))
    .filter((id): id is Tenant['id'] => id !== null && id !== undefined)
}

/**
 * Get all tenant IDs for a user (regardless of role)
 */
export const getAllUserTenantIDs = (user: User | null | undefined): Tenant['id'][] => {
  if (!user?.tenants) return []
  return user.tenants
    .map((t) => extractID(t.tenant))
    .filter((id): id is Tenant['id'] => id !== null && id !== undefined)
}

/**
 * Check if user is a tenant admin in any tenant
 */
export const isTenantAdmin = (user: User | null | undefined): boolean => {
  return hasTenantRole(user, 'admin')
}

/**
 * Check if user is a caregiver in any tenant
 */
export const isCaregiver = (user: User | null | undefined): boolean => {
  return hasTenantRole(user, 'caregiver')
}

/**
 * Check if user is kitchen staff in any tenant
 */
export const isKitchenStaff = (user: User | null | undefined): boolean => {
  return hasTenantRole(user, 'kitchen')
}

/**
 * Check if user can access kitchen features (admin or kitchen role)
 */
export const canAccessKitchen = (user: User | null | undefined): boolean => {
  return hasTenantRole(user, 'admin') || hasTenantRole(user, 'kitchen')
}

/**
 * Check if user can create meal orders (admin or caregiver role)
 */
export const canCreateOrders = (user: User | null | undefined): boolean => {
  return hasTenantRole(user, 'admin') || hasTenantRole(user, 'caregiver')
}
