// src/app/(payload)/api/youtube/dashboard/route.ts

import { getPayload } from 'payload'
import config from '@payload-config'
import { NextRequest, NextResponse } from 'next/server'

interface UserWithYouTubeRole {
  id: number
  isSuperAdmin?: boolean
  youtubeRole?: string
}

/**
 * GET /api/youtube/dashboard
 *
 * Liefert Dashboard-Daten für das YouTube Operations Hub:
 * - Aktive Kanäle
 * - Pipeline-Status (Anzahl Videos pro Status)
 * - Ausstehende Freigaben (für Manager)
 * - Überfällige Tasks
 * - Videos dieser Woche
 * - Gesamtzahl offener Tasks
 */
export async function GET(req: NextRequest) {
  try {
    const payload = await getPayload({ config })
    const { user } = await payload.auth({ headers: req.headers })

    if (!user) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
    }

    const typedUser = user as UserWithYouTubeRole

    // Prüfe YouTube-Zugriff
    if (!typedUser.isSuperAdmin && (!typedUser.youtubeRole || typedUser.youtubeRole === 'none')) {
      return NextResponse.json({ error: 'No YouTube access' }, { status: 403 })
    }

    // Kanäle abrufen
    const channels = await payload.find({
      collection: 'youtube-channels',
      where: { status: { equals: 'active' } },
      depth: 0,
    })

    // Pipeline-Status zählen (parallel für Performance)
    const [idea, scriptDraft, review, production, editing, ready, published] = await Promise.all([
      payload.count({ collection: 'youtube-content', where: { status: { equals: 'idea' } } }),
      payload.count({ collection: 'youtube-content', where: { status: { equals: 'script_draft' } } }),
      payload.count({
        collection: 'youtube-content',
        where: { status: { in: ['script_review', 'final_review'] } },
      }),
      payload.count({
        collection: 'youtube-content',
        where: { status: { in: ['shoot_scheduled', 'shot'] } },
      }),
      payload.count({
        collection: 'youtube-content',
        where: { status: { in: ['rough_cut', 'fine_cut'] } },
      }),
      payload.count({ collection: 'youtube-content', where: { status: { equals: 'approved' } } }),
      payload.count({ collection: 'youtube-content', where: { status: { equals: 'published' } } }),
    ])

    // Ausstehende Freigaben für Manager
    const pendingApprovals =
      typedUser.youtubeRole === 'manager' || typedUser.isSuperAdmin
        ? await payload.find({
            collection: 'youtube-content',
            where: {
              or: [{ status: { equals: 'script_review' } }, { status: { equals: 'final_review' } }],
            },
            limit: 10,
            depth: 1,
          })
        : { docs: [] }

    // Überfällige Tasks
    const overdueTasks = await payload.find({
      collection: 'yt-tasks',
      where: {
        and: [
          { status: { not_in: ['done', 'cancelled'] } },
          { dueDate: { less_than: new Date().toISOString() } },
        ],
      },
      depth: 1,
      limit: 20,
    })

    // Videos diese Woche geplant
    const weekStart = new Date()
    weekStart.setHours(0, 0, 0, 0)
    const weekEnd = new Date(weekStart)
    weekEnd.setDate(weekEnd.getDate() + 7)

    const thisWeekVideos = await payload.find({
      collection: 'youtube-content',
      where: {
        scheduledPublishDate: {
          greater_than_equal: weekStart.toISOString(),
          less_than: weekEnd.toISOString(),
        },
      },
      sort: 'scheduledPublishDate',
      depth: 1,
      limit: 20,
    })

    // Offene Tasks zählen
    const tasksTotal = await payload.count({
      collection: 'yt-tasks',
      where: { status: { not_equals: 'done' } },
    })

    return NextResponse.json({
      channels: channels.docs,
      pipeline: {
        idea: idea.totalDocs,
        script: scriptDraft.totalDocs,
        review: review.totalDocs,
        production: production.totalDocs,
        editing: editing.totalDocs,
        ready: ready.totalDocs,
        published: published.totalDocs,
      },
      pendingApprovals: pendingApprovals.docs,
      overdueTasks: overdueTasks.docs,
      thisWeekVideos: thisWeekVideos.docs,
      tasksTotal: tasksTotal.totalDocs,
    })
  } catch (error) {
    console.error('[YouTube Dashboard] Error:', error)
    return NextResponse.json(
      { error: error instanceof Error ? error.message : 'Unknown error' },
      { status: 500 }
    )
  }
}
