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 id, type, title, description, link, is_read, created_at, context_id, context_type
       FROM notifications
       WHERE user_id = $1
       ORDER BY created_at DESC
       LIMIT 50`,
      [user.id],
    )

    const notifications = result.rows.map((r: any) => ({
      id: r.id,
      type: r.type,
      title: r.title,
      description: r.description,
      link: r.link,
      read: r.is_read,
      timestamp: r.created_at,
      contextId: r.context_id,
      contextType: r.context_type,
    }))

    const unreadResult = await query(
      `SELECT COUNT(*) AS count FROM notifications WHERE user_id = $1 AND is_read = FALSE`,
      [user.id],
    )

    return NextResponse.json({
      notifications,
      unreadCount: parseInt(unreadResult.rows[0].count, 10),
    })
  } catch (error) {
    console.error("Notifications GET error:", error)
    return NextResponse.json({ error: "Failed to load notifications" }, { status: 500 })
  }
}

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

    const { type, title, description, link, userId } = await request.json()
    const isAdmin = user.role === "admin" || user.role === "super_admin"
    const targetUserId = (userId && isAdmin) ? userId : user.id

    const result = await query(
      `INSERT INTO notifications (user_id, type, title, description, link)
       VALUES ($1, $2, $3, $4, $5)
       RETURNING id, type, title, description, link, is_read, created_at`,
      [targetUserId, type, title, description || null, link || null],
    )

    const notif = result.rows[0]
    return NextResponse.json({
      id: notif.id,
      type: notif.type,
      title: notif.title,
      description: notif.description,
      link: notif.link,
      read: notif.is_read,
      timestamp: notif.created_at,
    }, { status: 201 })
  } catch (error) {
    console.error("Notifications POST error:", error)
    return NextResponse.json({ error: "Failed to create notification" }, { status: 500 })
  }
}

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

    await query(
      `UPDATE notifications SET is_read = TRUE WHERE user_id = $1 AND is_read = FALSE`,
      [user.id],
    )

    return NextResponse.json({ success: true })
  } catch (error) {
    console.error("Notifications PATCH error:", error)
    return NextResponse.json({ error: "Failed to mark all as read" }, { status: 500 })
  }
}
