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 lead_assigned, lead_status, note_added, daily_digest, weekly_report
       FROM notification_preferences
       WHERE user_id = $1`,
      [user.id],
    )

    if (result.rowCount === 0) {
      return NextResponse.json({
        leadAssigned: true,
        leadStatus: true,
        noteAdded: false,
        dailyDigest: false,
        weeklyReport: true,
      })
    }

    const r = result.rows[0]
    return NextResponse.json({
      leadAssigned: r.lead_assigned,
      leadStatus: r.lead_status,
      noteAdded: r.note_added,
      dailyDigest: r.daily_digest,
      weeklyReport: r.weekly_report,
    })
  } 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 notification_preferences (user_id, lead_assigned, lead_status, note_added, daily_digest, weekly_report, updated_at)
       VALUES ($1, $2, $3, $4, $5, $6, NOW())
       ON CONFLICT (user_id)
       DO UPDATE SET lead_assigned = $2, lead_status = $3, note_added = $4,
                     daily_digest = $5, weekly_report = $6, updated_at = NOW()`,
      [
        user.id,
        body.leadAssigned ?? true,
        body.leadStatus ?? true,
        body.noteAdded ?? false,
        body.dailyDigest ?? false,
        body.weeklyReport ?? true,
      ],
    )

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