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

export async function GET(request: NextRequest, { params }: { params: Promise<{ id: string }> }) {
  try {
    const { id } = await params
    const result = await sql`SELECT * FROM genres WHERE id = ${id}`

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

    return NextResponse.json({ genre: result[0] })
  } catch (error) {
    console.error("Error fetching genre:", error)
    return NextResponse.json({ error: "Internal server error" }, { status: 500 })
  }
}

export async function PUT(request: NextRequest, { params }: { params: Promise<{ id: string }> }) {
  try {
    const { id } = await params
    const body = await request.json()
    const { name, slug, description, color, is_featured } = body

    const updates: string[] = []
    const values: any[] = []

    if (name !== undefined) {
      values.push(name)
      updates.push(`name = $${values.length}`)
    }
    if (slug !== undefined) {
      values.push(slug)
      updates.push(`slug = $${values.length}`)
    }
    if (description !== undefined) {
      values.push(description)
      updates.push(`description = $${values.length}`)
    }
    if (color !== undefined) {
      values.push(color)
      updates.push(`color = $${values.length}`)
    }
    if (is_featured !== undefined) {
      values.push(is_featured)
      updates.push(`is_featured = $${values.length}`)
    }

    if (updates.length === 0) {
      return NextResponse.json({ error: "No fields to update" }, { status: 400 })
    }

    values.push(id)
    const query = `UPDATE genres SET ${updates.join(", ")} WHERE id = $${values.length} RETURNING *`

    const result = await sql(query, values)

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

    return NextResponse.json({ data: result[0] })
  } catch (error) {
    console.error("Error updating genre:", error)
    return NextResponse.json({ error: "Internal server error" }, { status: 500 })
  }
}

export async function DELETE(request: NextRequest, { params }: { params: Promise<{ id: string }> }) {
  try {
    const { id } = await params
    const result = await sql`DELETE FROM genres WHERE id = ${id} RETURNING id`

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

    return NextResponse.json({ success: true })
  } catch (error) {
    console.error("Error deleting genre:", error)
    return NextResponse.json({ error: "Internal server error" }, { status: 500 })
  }
}
