// src/lib/communityAccess.ts

import type { Access } from 'payload'

interface UserWithRoles {
  id: number
  isSuperAdmin?: boolean
  is_super_admin?: boolean
  youtubeRole?: 'none' | 'viewer' | 'editor' | 'producer' | 'creator' | 'manager'
  youtube_role?: 'none' | 'viewer' | 'editor' | 'producer' | 'creator' | 'manager'
  communityRole?: 'none' | 'viewer' | 'moderator' | 'manager'
  community_role?: 'none' | 'viewer' | 'moderator' | 'manager'
  roles?: string[]
}

const checkIsSuperAdmin = (user: UserWithRoles | null): boolean => {
  if (!user) return false
  return Boolean(user.isSuperAdmin || user.is_super_admin)
}

const getCommunityRole = (user: UserWithRoles | null): string | undefined => {
  if (!user) return undefined
  return user.communityRole || user.community_role
}

const getYouTubeRole = (user: UserWithRoles | null): string | undefined => {
  if (!user) return undefined
  return user.youtubeRole || user.youtube_role
}

function getLegacyCommunityRole(user: UserWithRoles | null): 'none' | 'viewer' | 'moderator' | 'manager' {
  if (!user?.roles?.length) return 'none'
  if (user.roles.includes('admin') || user.roles.includes('community_manager')) return 'manager'
  if (user.roles.includes('community_agent')) return 'moderator'
  return 'none'
}

/**
 * Einheitlicher Rollen-Check für Community APIs.
 * Unterstützt camelCase/snake_case Felder und Legacy-Rollenlisten.
 */
export function hasCommunityApiAccess(
  user: UserWithRoles | null,
  minimumRole: 'viewer' | 'moderator' | 'manager' = 'viewer',
): boolean {
  if (!user) return false
  if (checkIsSuperAdmin(user)) return true

  const roleOrder: Record<string, number> = {
    none: 0,
    viewer: 1,
    moderator: 2,
    manager: 3,
  }

  const communityRole = getCommunityRole(user) || getLegacyCommunityRole(user)
  const ytRole = getYouTubeRole(user)
  const ytCommunityLevel =
    ytRole === 'manager'
      ? 'manager'
      : ytRole === 'creator' || ytRole === 'producer' || ytRole === 'editor'
        ? 'moderator'
        : ytRole === 'viewer'
          ? 'viewer'
          : 'none'

  const effectiveRole = roleOrder[communityRole] >= roleOrder[ytCommunityLevel] ? communityRole : ytCommunityLevel
  return roleOrder[effectiveRole] >= roleOrder[minimumRole]
}

/**
 * Prüft ob User Community-Manager oder Super-Admin ist
 */
export const isCommunityManager: Access = ({ req }) => {
  const user = req.user as UserWithRoles | null
  return hasCommunityApiAccess(user, 'manager')
}

/**
 * Prüft ob User mindestens Moderator-Rechte hat
 */
export const isCommunityModeratorOrAbove: Access = ({ req }) => {
  const user = req.user as UserWithRoles | null
  return hasCommunityApiAccess(user, 'moderator')
}

/**
 * Prüft ob User Zugriff auf Community-Features hat (mindestens Viewer)
 */
export const hasCommunityAccess: Access = ({ req }) => {
  const user = req.user as UserWithRoles | null
  return hasCommunityApiAccess(user, 'viewer')
}

/**
 * Zugriff auf zugewiesene Interactions
 */
export const canAccessAssignedInteractions: Access = ({ req }) => {
  const user = req.user as UserWithRoles | null
  if (!user) return false
  if (checkIsSuperAdmin(user)) return true
  if (getYouTubeRole(user) === 'manager') return true
  if (getCommunityRole(user) === 'manager') return true

  // Für andere Rollen: Nur zugewiesene Interactions
  return {
    or: [
      { assignedTo: { equals: user.id } },
      { 'response.sentBy': { equals: user.id } },
    ],
  } as any
}
