import { NextRequest, NextResponse } from "next/server"
import { getSessionUser } from "@/lib/auth"
import { query } from "@/lib/db"

export async function GET() {
  try {
    const user = await getSessionUser()
    if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 })

    const result = await query(
      `SELECT preferences->>'website_theme' AS website_theme FROM users WHERE id = $1`,
      [user.id],
    )

    const websiteTheme = result.rows[0]?.website_theme || "starforce"
    return NextResponse.json({ websiteTheme })
  } catch (error) {
    console.error("Website theme GET error:", error)
    return NextResponse.json({ error: "Failed to load website theme" }, { status: 500 })
  }
}

export async function PUT(request: NextRequest) {
  try {
    const user = await getSessionUser()
    if (!user) return NextResponse.json({ error: "Unauthorized" }, { status: 401 })

    const body = await request.json()
    const theme = body.websiteTheme || "starforce"

    await query(
      `UPDATE users SET preferences = preferences || $2::jsonb WHERE id = $1`,
      [user.id, JSON.stringify({ website_theme: theme })],
    )

    return NextResponse.json({ success: true, websiteTheme: theme })
  } catch (error) {
    console.error("Website theme PUT error:", error)
    return NextResponse.json({ error: "Failed to save website theme" }, { status: 500 })
  }
}
