// src/lib/youtubeAccess.ts

import type { Access } from 'payload'

interface UserWithYouTubeRole {
  id: number
  isSuperAdmin?: boolean
  is_super_admin?: boolean // Alternative snake_case Variante
  youtubeRole?: 'none' | 'viewer' | 'editor' | 'producer' | 'creator' | 'manager'
  youtube_role?: 'none' | 'viewer' | 'editor' | 'producer' | 'creator' | 'manager' // Alternative snake_case
  youtubeChannels?: Array<{ id: number } | number>
}

/**
 * Hilfsfunktion: Prüft ob User Super-Admin ist (beide Feldnamen)
 */
const checkIsSuperAdmin = (user: UserWithYouTubeRole | null): boolean => {
  if (!user) return false
  return Boolean(user.isSuperAdmin || user.is_super_admin)
}

/**
 * Hilfsfunktion: Holt die YouTube-Rolle des Users (beide Feldnamen)
 */
const getYouTubeRole = (user: UserWithYouTubeRole | null): string | undefined => {
  if (!user) return undefined
  return user.youtubeRole || user.youtube_role
}

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

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

/**
 * Prüft ob User Zugriff auf YouTube-Content hat (mindestens Viewer)
 */
export const hasYouTubeAccess: Access = ({ req }) => {
  const user = req.user as UserWithYouTubeRole | null
  if (!user) return false
  if (checkIsSuperAdmin(user)) return true
  const role = getYouTubeRole(user)
  return role !== 'none' && role !== undefined
}

/**
 * Zugriff auf zugewiesene Videos/Tasks oder als Manager
 */
export const canAccessAssignedContent: Access = ({ req }) => {
  const user = req.user as UserWithYouTubeRole | null
  if (!user) return false
  if (checkIsSuperAdmin(user)) return true
  if (getYouTubeRole(user) === 'manager') return true

  // Für andere Rollen: Nur zugewiesene Inhalte
  return {
    or: [
      { assignedTo: { equals: user.id } },
      { createdBy: { equals: user.id } },
    ],
  } as any
}

/**
 * Zugriff auf eigene Benachrichtigungen
 */
export const canAccessOwnNotifications: Access = ({ req }) => {
  const user = req.user as UserWithYouTubeRole | null
  if (!user) return false
  if (checkIsSuperAdmin(user)) return true
  return { recipient: { equals: user.id } }
}
