// src/app/(payload)/api/youtube/my-tasks/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/my-tasks
 *
 * Liefert alle offenen Tasks des eingeloggten Users.
 * Sortiert nach Fälligkeitsdatum.
 */
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 })
    }

    const tasks = await payload.find({
      collection: 'yt-tasks',
      where: {
        and: [
          { assignedTo: { equals: user.id } },
          { status: { not_in: ['done', 'cancelled'] } },
        ],
      },
      sort: 'dueDate',
      depth: 2, // Video und Channel laden
    })

    return NextResponse.json({
      tasks: tasks.docs,
      total: tasks.totalDocs,
    })
  } catch (error) {
    console.error('[YouTube My-Tasks] Error:', error)
    return NextResponse.json(
      { error: error instanceof Error ? error.message : 'Unknown error' },
      { status: 500 }
    )
  }
}
