import { NextResponse } from "next/server"
import { sql } from "@/lib/db"

export async function GET(request: Request) {
  try {
    const { searchParams } = new URL(request.url)
    const status = searchParams.get("status")
    const artistId = searchParams.get("artist_id")
    const search = searchParams.get("search")
    const limit = Math.min(Number(searchParams.get("limit")) || 20, 100)
    const offset = Number(searchParams.get("offset")) || 0
    const includeAll = searchParams.get("include_all") === "true" // For admin view

    let videos
    let countResult

    if (includeAll) {
      // Admin view - show all videos regardless of status
      if (search) {
        const searchPattern = `%${search}%`
        videos = await sql`
          SELECT v.*, a.name as artist_name, a.avatar_url as artist_avatar
          FROM videos v
          LEFT JOIN artists a ON v.artist_id = a.id
          WHERE v.title ILIKE ${searchPattern} OR v.description ILIKE ${searchPattern}
          ORDER BY v.created_at DESC
          LIMIT ${limit} OFFSET ${offset}
        `
        countResult = await sql`
          SELECT COUNT(*) as total FROM videos v
          WHERE v.title ILIKE ${searchPattern} OR v.description ILIKE ${searchPattern}
        `
      } else if (status) {
        videos = await sql`
          SELECT v.*, a.name as artist_name, a.avatar_url as artist_avatar
          FROM videos v
          LEFT JOIN artists a ON v.artist_id = a.id
          WHERE v.status = ${status}
          ORDER BY v.created_at DESC
          LIMIT ${limit} OFFSET ${offset}
        `
        countResult = await sql`
          SELECT COUNT(*) as total FROM videos v WHERE v.status = ${status}
        `
      } else {
        videos = await sql`
          SELECT v.*, a.name as artist_name, a.avatar_url as artist_avatar
          FROM videos v
          LEFT JOIN artists a ON v.artist_id = a.id
          ORDER BY v.created_at DESC
          LIMIT ${limit} OFFSET ${offset}
        `
        countResult = await sql`SELECT COUNT(*) as total FROM videos`
      }
    } else if (artistId) {
      // Artist view - show all their videos
      videos = await sql`
        SELECT v.*, a.name as artist_name, a.avatar_url as artist_avatar
        FROM videos v
        LEFT JOIN artists a ON v.artist_id = a.id
        WHERE v.artist_id = ${artistId}
        ORDER BY v.created_at DESC
        LIMIT ${limit} OFFSET ${offset}
      `
      countResult = await sql`
        SELECT COUNT(*) as total FROM videos v WHERE v.artist_id = ${artistId}
      `
    } else {
      // Public view - only published videos
      if (search) {
        const searchPattern = `%${search}%`
        videos = await sql`
          SELECT v.*, a.name as artist_name, a.avatar_url as artist_avatar
          FROM videos v
          LEFT JOIN artists a ON v.artist_id = a.id
          WHERE v.status = 'published' AND (v.title ILIKE ${searchPattern} OR v.description ILIKE ${searchPattern})
          ORDER BY v.created_at DESC
          LIMIT ${limit} OFFSET ${offset}
        `
        countResult = await sql`
          SELECT COUNT(*) as total FROM videos v
          WHERE v.status = 'published' AND (v.title ILIKE ${searchPattern} OR v.description ILIKE ${searchPattern})
        `
      } else {
        videos = await sql`
          SELECT v.*, a.name as artist_name, a.avatar_url as artist_avatar
          FROM videos v
          LEFT JOIN artists a ON v.artist_id = a.id
          WHERE v.status = 'published'
          ORDER BY v.created_at DESC
          LIMIT ${limit} OFFSET ${offset}
        `
        countResult = await sql`
          SELECT COUNT(*) as total FROM videos v WHERE v.status = 'published'
        `
      }
    }

    const total = Number(countResult[0]?.total || 0)

    return NextResponse.json({
      videos,
      pagination: {
        total,
        limit,
        offset,
        hasMore: offset + videos.length < total,
      },
    })
  } catch (error: any) {
    console.error("[Videos API] Error:", error)
    return NextResponse.json({ error: "Failed to fetch videos" }, { status: 500 })
  }
}

export async function POST(request: Request) {
  try {
    const body = await request.json()
    const {
      title,
      description,
      artist_id,
      video_url,
      thumbnail_url,
      duration_ms,
      category,
      tags,
      is_free = true,
      price_fcfa = 0,
    } = body

    if (!title || !video_url) {
      return NextResponse.json({ error: "Title and video URL are required" }, { status: 400 })
    }

    const result = await sql`
      INSERT INTO videos (
        title, description, artist_id, video_url, thumbnail_url,
        duration_ms, category, tags, is_free, price_fcfa, status
      )
      VALUES (
        ${title}, ${description || null}, ${artist_id || null}, ${video_url}, ${thumbnail_url || null},
        ${duration_ms || null}, ${category || null}, ${tags || null}, ${is_free}, ${price_fcfa || 0}, 'pending'
      )
      RETURNING *
    `

    return NextResponse.json({ video: result[0] }, { status: 201 })
  } catch (error: any) {
    console.error("[Videos API] Create error:", error)
    return NextResponse.json({ error: "Failed to create video" }, { status: 500 })
  }
}
