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

import { getPayload } from 'payload'
import config from '@payload-config'
import { NextRequest, NextResponse } from 'next/server'
import { calculateCapacity, type CapacityInput } from '@/lib/youtube/capacity-calculator'

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

const DEFAULT_HOURS_PER_TASK = 2
const DEFAULT_AVAILABLE_HOURS_PER_WEEK = 40

/**
 * GET /api/youtube/capacity
 *
 * Returns team capacity data for all users with a YouTube role.
 * Calculates utilization based on active tasks and estimated hours.
 */
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 })
    }

    // Find all users with a YouTube role
    const users = await payload.find({
      collection: 'users',
      where: {
        youtubeRole: { exists: true },
      },
      limit: 50,
      depth: 0,
    })

    const capacities = await Promise.all(
      users.docs.map(async (u) => {
        const typedUser = u as unknown as UserWithYouTubeRole

        // Count active tasks
        const tasks = await payload.count({
          collection: 'yt-tasks',
          where: {
            assignedTo: { equals: typedUser.id },
            status: { in: ['todo', 'in_progress'] },
          },
        })

        // Count videos in pipeline (exclude terminal and initial states)
        const videos = await payload.count({
          collection: 'youtube-content',
          where: {
            assignedTo: { equals: typedUser.id },
            status: { not_in: ['published', 'tracked', 'discarded', 'idea'] },
          },
        })

        const input: CapacityInput = {
          userId: typedUser.id,
          userName: typedUser.email ?? `User ${typedUser.id}`,
          activeTasks: tasks.totalDocs,
          estimatedHours: tasks.totalDocs * DEFAULT_HOURS_PER_TASK,
          videosInPipeline: videos.totalDocs,
          availableHoursPerWeek: DEFAULT_AVAILABLE_HOURS_PER_WEEK,
        }

        return calculateCapacity(input)
      }),
    )

    return NextResponse.json({
      success: true,
      team: capacities,
      summary: {
        totalMembers: capacities.length,
        overloaded: capacities.filter((c) => c.status === 'red').length,
        atCapacity: capacities.filter((c) => c.status === 'yellow').length,
        available: capacities.filter((c) => c.status === 'green').length,
      },
    })
  } catch (error) {
    console.error('[Capacity API] Error:', error)
    return NextResponse.json(
      { error: error instanceof Error ? error.message : 'Unknown error' },
      { status: 500 },
    )
  }
}
