// ── Settings: Website Theme ──────────────────────────────────────────────────
// GET /api/settings/website-theme  — Get the current user's theme preference
// PUT /api/settings/website-theme  — Update theme preference (stored in JSONB)
//
// Auth: authenticated
// Reads and writes the website_theme and color_theme keys inside the user's
// preferences JSONB column, preserving other preference data.

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

// ── GET ──────────────────────────────────────────────────────────────────────

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

    // Extract website_theme and color_theme from the JSONB preferences column
    const result = await query(
      `SELECT preferences->>'website_theme' AS website_theme, preferences->>'color_theme' AS color_theme FROM users WHERE id = $1`,
      [user.id],
    )

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

// ── PUT ──────────────────────────────────────────────────────────────────────

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 update: Record<string, string> = {}
    if (body.websiteTheme !== undefined) {
      update.website_theme = body.websiteTheme || "default"
    }
    if (body.colorTheme !== undefined) {
      update.color_theme = body.colorTheme || "default"
    }

    // Merge into the existing JSONB preferences using || operator
    if (Object.keys(update).length > 0) {
      await query(
        `UPDATE users SET preferences = preferences || $2::jsonb WHERE id = $1`,
        [user.id, JSON.stringify(update)],
      )
    }

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

    return NextResponse.json({
      success: true,
      websiteTheme: result.rows[0]?.website_theme || "default",
      colorTheme: result.rows[0]?.color_theme || null,
    })
  } catch (error) {
    console.error("Website theme PUT error:", error)
    return NextResponse.json({ error: "Failed to save website theme" }, { status: 500 })
  }
}
