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

export async function GET(request: NextRequest, { params }: { params: Promise<{ id: string }> }) {
  try {
    const adminId = await getAdminUser(request)
    if (!adminId) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 })
    }

    const { id } = await params
    const result = await sql`SELECT * FROM categories WHERE id = ${id}`
    if (result.length === 0) {
      return NextResponse.json({ error: "Category not found" }, { status: 404 })
    }
    return NextResponse.json(result[0])
  } catch (error) {
    console.error("Error fetching category:", error)
    return NextResponse.json({ error: "Failed to fetch category" }, { status: 500 })
  }
}

export async function PUT(request: NextRequest, { params }: { params: Promise<{ id: string }> }) {
  try {
    const adminId = await getAdminUser(request)
    if (!adminId) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 })
    }

    const { id } = await params
    const body = await request.json()
    const { name, slug, description, icon, color, is_visible } = body

    const result = await sql`
      UPDATE categories 
      SET name = ${name}, slug = ${slug}, description = ${description || null}, 
          icon = ${icon || null}, color = ${color || null}, is_visible = ${is_visible ?? true},
          updated_at = NOW()
      WHERE id = ${id}
      RETURNING *
    `
    return NextResponse.json(result[0])
  } catch (error) {
    console.error("Error updating category:", error)
    return NextResponse.json({ error: "Failed to update category" }, { status: 500 })
  }
}

export async function PATCH(request: NextRequest, { params }: { params: Promise<{ id: string }> }) {
  try {
    const adminId = await getAdminUser(request)
    if (!adminId) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 })
    }

    const { id } = await params
    const body = await request.json()

    const current = await sql`SELECT * FROM categories WHERE id = ${id}`
    if (current.length === 0) {
      return NextResponse.json({ error: "Category not found" }, { status: 404 })
    }

    const cat = current[0]
    const name = body.name !== undefined ? body.name : cat.name
    const slug = body.slug !== undefined ? body.slug : cat.slug
    const description = body.description !== undefined ? body.description : cat.description
    const icon = body.icon !== undefined ? body.icon : cat.icon
    const color = body.color !== undefined ? body.color : cat.color
    const is_visible = body.is_visible !== undefined ? body.is_visible : cat.is_visible

    const result = await sql`
      UPDATE categories 
      SET name = ${name}, slug = ${slug}, description = ${description}, 
          icon = ${icon}, color = ${color}, is_visible = ${is_visible},
          updated_at = NOW()
      WHERE id = ${id}
      RETURNING *
    `
    return NextResponse.json(result[0])
  } catch (error) {
    console.error("Error updating category:", error)
    return NextResponse.json({ error: "Failed to update category" }, { status: 500 })
  }
}

export async function DELETE(request: NextRequest, { params }: { params: Promise<{ id: string }> }) {
  try {
    const adminId = await getAdminUser(request)
    if (!adminId) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 })
    }

    const { id } = await params
    await sql`DELETE FROM categories WHERE id = ${id}`
    return NextResponse.json({ success: true })
  } catch (error) {
    console.error("Error deleting category:", error)
    return NextResponse.json({ error: "Failed to delete category" }, { status: 500 })
  }
}
