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

export async function GET(request: Request, { params }: { params: Promise<{ id: string }> }) {
  try {
    const { id } = await params

    const result = 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.id = ${id}
    `

    if (result.length === 0) {
      return NextResponse.json({ error: "Video not found" }, { status: 404 })
    }

    return NextResponse.json({ video: result[0] })
  } catch (error: any) {
    console.error("[Video API] Error:", error)
    return NextResponse.json({ error: "Failed to fetch video" }, { status: 500 })
  }
}

export async function PATCH(request: Request, { params }: { params: Promise<{ id: string }> }) {
  try {
    const { id } = await params
    const body = await request.json()

    const validStatuses = ["draft", "pending", "published", "archived", "rejected"]
    const allowedFields = [
      "title",
      "description",
      "thumbnail_url",
      "status",
      "is_free",
      "price_fcfa",
      "rejection_reason",
    ]

    // Validate status if provided
    if (body.status && !validStatuses.includes(body.status)) {
      return NextResponse.json(
        { error: `Invalid status. Allowed: ${validStatuses.join(", ")}` },
        { status: 400 }
      )
    }

    // Build update based on provided fields
    let result

    if (body.status !== undefined && Object.keys(body).length === 1) {
      result = await sql`
        UPDATE videos
        SET status = ${body.status}, updated_at = CURRENT_TIMESTAMP
        WHERE id = ${id}
        RETURNING *
      `
    } else if (body.title !== undefined && body.status !== undefined) {
      result = await sql`
        UPDATE videos
        SET title = ${body.title}, status = ${body.status}, updated_at = CURRENT_TIMESTAMP
        WHERE id = ${id}
        RETURNING *
      `
    } else if (body.title !== undefined) {
      result = await sql`
        UPDATE videos
        SET title = ${body.title}, updated_at = CURRENT_TIMESTAMP
        WHERE id = ${id}
        RETURNING *
      `
    } else if (body.is_free !== undefined && body.price_fcfa !== undefined) {
      result = await sql`
        UPDATE videos
        SET is_free = ${body.is_free}, price_fcfa = ${body.price_fcfa}, updated_at = CURRENT_TIMESTAMP
        WHERE id = ${id}
        RETURNING *
      `
    } else if (body.is_free !== undefined) {
      result = await sql`
        UPDATE videos
        SET is_free = ${body.is_free}, updated_at = CURRENT_TIMESTAMP
        WHERE id = ${id}
        RETURNING *
      `
    } else if (body.rejection_reason !== undefined) {
      result = await sql`
        UPDATE videos
        SET status = 'rejected', rejection_reason = ${body.rejection_reason}, updated_at = CURRENT_TIMESTAMP
        WHERE id = ${id}
        RETURNING *
      `
    } else if (body.description !== undefined) {
      result = await sql`
        UPDATE videos
        SET description = ${body.description}, updated_at = CURRENT_TIMESTAMP
        WHERE id = ${id}
        RETURNING *
      `
    } else if (body.thumbnail_url !== undefined) {
      result = await sql`
        UPDATE videos
        SET thumbnail_url = ${body.thumbnail_url}, updated_at = CURRENT_TIMESTAMP
        WHERE id = ${id}
        RETURNING *
      `
    } else {
      return NextResponse.json({ error: "No valid fields to update" }, { status: 400 })
    }

    if (result.length === 0) {
      return NextResponse.json({ error: "Video not found" }, { status: 404 })
    }

    return NextResponse.json({ video: result[0] })
  } catch (error: any) {
    console.error("[Video API] Update error:", error)
    return NextResponse.json({ error: "Failed to update video" }, { status: 500 })
  }
}

export async function DELETE(request: Request, { params }: { params: Promise<{ id: string }> }) {
  try {
    const { id } = await params

    const result = await sql`
      DELETE FROM videos WHERE id = ${id} RETURNING id
    `

    if (result.length === 0) {
      return NextResponse.json({ error: "Video not found" }, { status: 404 })
    }

    return NextResponse.json({ success: true })
  } catch (error: any) {
    console.error("[Video API] Delete error:", error)
    return NextResponse.json({ error: "Failed to delete video" }, { status: 500 })
  }
}
