// src/app/(payload)/api/youtube/complete-task/[id]/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
}

interface RouteParams {
  params: Promise<{ id: string }>
}

/**
 * POST /api/youtube/complete-task/[id]
 *
 * Markiert einen Task als erledigt.
 * Nur der zugewiesene User oder ein Manager/Super-Admin kann dies tun.
 */
export async function POST(req: NextRequest, { params }: RouteParams) {
  try {
    const { id: taskId } = await params
    const payload = await getPayload({ config })
    const { user } = await payload.auth({ headers: req.headers })

    if (!user || !taskId) {
      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 task = await payload.findByID({
      collection: 'yt-tasks',
      id: taskId,
      depth: 0,
    })

    if (!task) {
      return NextResponse.json({ error: 'Task not found' }, { status: 404 })
    }

    // Prüfen ob User berechtigt ist
    const assignedId = typeof task.assignedTo === 'object' ? task.assignedTo.id : task.assignedTo

    const canComplete =
      typedUser.isSuperAdmin ||
      typedUser.youtubeRole === 'manager' ||
      assignedId === user.id

    if (!canComplete) {
      return NextResponse.json({ error: 'Forbidden' }, { status: 403 })
    }

    const updated = await payload.update({
      collection: 'yt-tasks',
      id: taskId,
      data: {
        status: 'done',
        completedAt: new Date().toISOString(),
        completedBy: user.id,
      },
    })

    return NextResponse.json({ success: true, task: updated })
  } catch (error) {
    console.error('[YouTube Complete-Task] Error:', error)
    return NextResponse.json(
      { error: error instanceof Error ? error.message : 'Unknown error' },
      { status: 500 }
    )
  }
}
