import { NextResponse } from "next/server"
import { getVideos, addVideo, getYoutubeThumbnail } from "@/lib/videos"
import { validateAdminToken } from "@/lib/admin-auth"

export const dynamic = "force-dynamic"

export async function GET() {
  const videos = getVideos()
  return NextResponse.json(videos)
}

export async function POST(request: Request) {
  const authHeader = request.headers.get("Authorization")
  const token = authHeader?.replace("Bearer ", "")

  if (!token || !validateAdminToken(token)) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 })
  }

  const body = await request.json()
  const { youtubeUrl, title, description } = body

  if (!youtubeUrl) {
    return NextResponse.json({ error: "YouTube URL is required" }, { status: 400 })
  }

  // Auto-fetch title from YouTube oEmbed if not provided
  let videoTitle = title || ""
  if (!videoTitle) {
    try {
      const oembedUrl = `https://www.youtube.com/oembed?url=${encodeURIComponent(youtubeUrl)}&format=json`
      const res = await fetch(oembedUrl)
      if (res.ok) {
        const data = await res.json()
        videoTitle = data.title || "Untitled Video"
      }
    } catch {
      videoTitle = "Untitled Video"
    }
  }

  const thumbnail = getYoutubeThumbnail(youtubeUrl)

  const video = addVideo({
    title: videoTitle,
    description: description || "",
    youtubeUrl,
    thumbnail,
  })

  return NextResponse.json(video, { status: 201 })
}
