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 timezone, date_format, items_per_page FROM user_preferences WHERE user_id = $1`,
      [user.id],
    )

    if (result.rowCount === 0) {
      return NextResponse.json({
        timezone: "america-los_angeles",
        dateFormat: "mdy",
        itemsPerPage: 20,
      })
    }

    const r = result.rows[0]
    return NextResponse.json({
      timezone: r.timezone,
      dateFormat: r.date_format,
      itemsPerPage: r.items_per_page,
    })
  } catch (error) {
    console.error("Preferences GET error:", error)
    return NextResponse.json({ error: "Failed to load preferences" }, { status: 500 })
  }
}

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

    const body = await request.json()

    await query(
      `INSERT INTO user_preferences (user_id, timezone, date_format, items_per_page, updated_at)
       VALUES ($1, $2, $3, $4, NOW())
       ON CONFLICT (user_id)
       DO UPDATE SET timezone = $2, date_format = $3, items_per_page = $4, updated_at = NOW()`,
      [
        user.id,
        body.timezone || "america-los_angeles",
        body.dateFormat || "mdy",
        body.itemsPerPage || 20,
      ],
    )

    return NextResponse.json({ success: true })
  } catch (error) {
    console.error("Preferences PATCH error:", error)
    return NextResponse.json({ error: "Failed to save preferences" }, { status: 500 })
  }
}
