import { NextRequest, NextResponse } from "next/server"
import { query } from "@/lib/db"
import { getPortalSession, isPortalError } from "../portal-utils"

export async function GET() {
  const session = await getPortalSession()
  if (isPortalError(session)) return session

  const tickets = await query(
    `SELECT id, title, description, severity, status, created_at, updated_at,
            resolution_notes
     FROM bug_reports
     WHERE reported_by = $1
     ORDER BY created_at DESC`,
    [session.userId],
  )

  return NextResponse.json({ tickets: tickets.rows })
}

export async function POST(request: NextRequest) {
  const session = await getPortalSession()
  if (isPortalError(session)) return session

  const { title, description, severity } = await request.json()

  if (!title || !description) {
    return NextResponse.json(
      { error: "Title and description are required" },
      { status: 400 },
    )
  }

  const validSeverities = ["low", "medium", "high", "critical"]
  const sev = validSeverities.includes(severity) ? severity : "medium"

  const result = await query(
    `INSERT INTO bug_reports (reported_by, title, description, severity, page_url)
     VALUES ($1, $2, $3, $4, $5)
     RETURNING id, title, description, severity, status, created_at`,
    [session.userId, title, description, sev, "/client-portal/support"],
  )

  return NextResponse.json({ ticket: result.rows[0] }, { status: 201 })
}
