// 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'
}

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
}

/**
 * Prüft ob User Community-Manager oder Super-Admin ist
 */
export const isCommunityManager: Access = ({ req }) => {
  const user = req.user as UserWithRoles | null
  if (!user) return false
  if (checkIsSuperAdmin(user)) return true
  // YouTube-Manager haben auch Community-Zugriff
  if (getYouTubeRole(user) === 'manager') return true
  return getCommunityRole(user) === 'manager'
}

/**
 * Prüft ob User mindestens Moderator-Rechte hat
 */
export const isCommunityModeratorOrAbove: Access = ({ req }) => {
  const user = req.user as UserWithRoles | null
  if (!user) return false
  if (checkIsSuperAdmin(user)) return true
  if (['manager', 'creator'].includes(getYouTubeRole(user) || '')) return true
  return ['moderator', 'manager'].includes(getCommunityRole(user) || '')
}

/**
 * Prüft ob User Zugriff auf Community-Features hat (mindestens Viewer)
 */
export const hasCommunityAccess: Access = ({ req }) => {
  const user = req.user as UserWithRoles | null
  if (!user) return false
  if (checkIsSuperAdmin(user)) return true
  const ytRole = getYouTubeRole(user)
  if (ytRole && ytRole !== 'none') return true
  const commRole = getCommunityRole(user)
  return commRole !== 'none' && commRole !== undefined
}

/**
 * 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 } },
    ],
  }
}
