// src/hooks/youtubeContent/createTasksOnStatusChange.ts

import type { CollectionAfterChangeHook } from 'payload'
import type { YtTask } from '@/payload-types'

type TaskType = NonNullable<YtTask['taskType']>
type AssignRole = 'creator' | 'producer' | 'editor' | 'manager'

interface TaskTemplate {
  title: string
  type: TaskType
  assignRole: AssignRole
}

/**
 * Task-Templates für jeden Video-Status
 * Definiert welche Aufgaben bei welchem Statuswechsel erstellt werden
 */
const TASK_TEMPLATES: Record<string, TaskTemplate[]> = {
  script_draft: [{ title: 'Skript schreiben', type: 'script_write', assignRole: 'creator' }],
  script_review: [{ title: 'Skript reviewen', type: 'script_review', assignRole: 'manager' }],
  script_approved: [{ title: 'Dreh vorbereiten', type: 'shoot_prep', assignRole: 'producer' }],
  shoot_scheduled: [{ title: 'Dreh durchführen', type: 'shoot', assignRole: 'producer' }],
  shot: [{ title: 'Rohschnitt erstellen', type: 'edit', assignRole: 'editor' }],
  rough_cut: [
    { title: 'Feinschnitt erstellen', type: 'edit', assignRole: 'editor' },
    { title: 'Grafiken erstellen', type: 'graphics', assignRole: 'editor' },
  ],
  fine_cut: [
    { title: 'Thumbnail erstellen', type: 'thumbnail', assignRole: 'editor' },
    { title: 'Final Review', type: 'review', assignRole: 'manager' },
  ],
  approved: [{ title: 'Video hochladen', type: 'upload', assignRole: 'manager' }],
  published: [
    { title: 'Performance nach 24h tracken', type: 'track', assignRole: 'manager' },
    { title: 'Kommentare beantworten', type: 'comments', assignRole: 'creator' },
  ],
}

interface UserWithYouTubeRole {
  id: number
  youtubeRole?: string
}

/**
 * Hook: Erstellt automatisch Tasks bei Video-Statuswechsel
 *
 * Wird aufgerufen nach jeder Änderung an einem YouTubeContent-Dokument.
 * Prüft ob sich der Status geändert hat und erstellt entsprechende Tasks.
 */
export const createTasksOnStatusChange: CollectionAfterChangeHook = async ({
  doc,
  previousDoc,
  req,
  operation,
}) => {
  // Nur bei Updates und wenn sich der Status geändert hat
  if (operation !== 'update' || doc.status === previousDoc?.status) {
    return doc
  }

  const tasks = TASK_TEMPLATES[doc.status]
  if (!tasks || tasks.length === 0) {
    return doc
  }

  // Mapping: Task-Rolle -> YouTube-Rolle
  const roleMapping: Record<string, string[]> = {
    creator: ['creator', 'manager'],
    producer: ['producer', 'manager'],
    editor: ['editor', 'manager'],
    manager: ['manager'],
  }

  /**
   * Findet einen User mit der passenden YouTube-Rolle
   */
  const getUserByYouTubeRole = async (role: string): Promise<number | null> => {
    const allowedRoles = roleMapping[role] || ['manager']

    // Wenn Video einem User zugewiesen ist, prüfe dessen Rolle
    if (doc.assignedTo) {
      try {
        const assignedUser = (await req.payload.findByID({
          collection: 'users',
          id: typeof doc.assignedTo === 'object' ? doc.assignedTo.id : doc.assignedTo,
          depth: 0,
        })) as UserWithYouTubeRole | null

        if (assignedUser?.youtubeRole && allowedRoles.includes(assignedUser.youtubeRole)) {
          return assignedUser.id
        }
      } catch (error) {
        console.error('[createTasksOnStatusChange] Error fetching assigned user:', error)
      }
    }

    // Sonst: Ersten User mit passender Rolle finden
    try {
      const users = await req.payload.find({
        collection: 'users',
        where: {
          youtubeRole: { in: allowedRoles },
        },
        limit: 1,
        depth: 0,
      })

      return users.docs[0]?.id || null
    } catch (error) {
      console.error('[createTasksOnStatusChange] Error finding user by role:', error)
      return null
    }
  }

  // Tasks erstellen
  for (const taskTemplate of tasks) {
    const assignedUserId = await getUserByYouTubeRole(taskTemplate.assignRole)

    if (assignedUserId) {
      const channelId = typeof doc.channel === 'object' ? doc.channel.id : doc.channel
      const videoTitle = typeof doc.title === 'string' ? doc.title : doc.title?.de || doc.title?.en || 'Video'

      try {
        await req.payload.create({
          collection: 'yt-tasks',
          data: {
            title: `${taskTemplate.title}: ${videoTitle}`,
            video: doc.id,
            channel: channelId,
            taskType: taskTemplate.type,
            status: 'todo',
            priority: doc.priority || 'normal',
            assignedTo: assignedUserId,
            dueDate: doc.scheduledPublishDate
              ? new Date(
                  new Date(doc.scheduledPublishDate).getTime() - 2 * 24 * 60 * 60 * 1000
                ).toISOString()
              : undefined,
          },
        })

        console.log(`[createTasksOnStatusChange] Created task: ${taskTemplate.title} for video ${doc.id}`)
      } catch (error) {
        console.error('[createTasksOnStatusChange] Error creating task:', error)
      }
    } else {
      console.warn(
        `[createTasksOnStatusChange] No user found for role ${taskTemplate.assignRole}, skipping task: ${taskTemplate.title}`
      )
    }
  }

  return doc
}
