/**
 * Support Tickets API - User-facing endpoints
 *
 * GET /api/support/tickets - List user's tickets
 * POST /api/support/tickets - Create new ticket
 *
 * All data access goes through Convex. No Prisma fallback.
 */

import { NextRequest, NextResponse } from "next/server";
import { auth } from "@/lib/auth";
import { getAuthenticatedUser } from "@/lib/utils/auth-helpers.util";
import {
  type TicketCategory,
  type TicketPriority,
} from "@/lib/services/support-tickets.service";
import { logger } from "@/lib/logger";
import { convexQuery, convexMutation } from "@/lib/convex-client";

export const dynamic = "force-dynamic";
export const runtime = "nodejs";

const VALID_CATEGORIES: TicketCategory[] = [
  "BILLING",
  "TECHNICAL",
  "FEATURE_REQUEST",
  "OTHER",
];
const VALID_PRIORITIES: TicketPriority[] = ["LOW", "NORMAL", "URGENT"];

/**
 * GET /api/support/tickets
 * List user's tickets with pagination and unread counts
 */
export async function GET(request: NextRequest) {
  try {
    const user = await getAuthenticatedUser(request, auth);
    if (!user) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }

    const userId = user.userId;
    const status = request.nextUrl.searchParams.get("status") ?? undefined;

    const result = await convexQuery("support/queries:getTickets", {
      userId,
      status,
      limit: 20,
    });

    if (result !== null) {
      // Map Convex _id to id and format dates for client compatibility
      const tickets = (result as Record<string, unknown>[]).map((t) => ({
        ...t,
        id: t._id ?? t.id,
        createdAt: t.createdAt ? new Date(t.createdAt as number).toISOString() : null,
        updatedAt: t.updatedAt ? new Date(t.updatedAt as number).toISOString() : null,
      }));
      return NextResponse.json({
        tickets,
        total: tickets.length,
        success: true,
      });
    }

    // Convex returned null — return empty
    return NextResponse.json({ tickets: [], total: 0, success: true });
  } catch (error) {
    logger.error("Failed to fetch user tickets", { error });
    return NextResponse.json(
      { error: "Failed to fetch tickets" },
      { status: 500 },
    );
  }
}

/**
 * POST /api/support/tickets
 * Create a new support ticket
 */
export async function POST(request: NextRequest) {
  try {
    const user = await getAuthenticatedUser(request, auth);
    if (!user) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }

    const userId = user.userId;
    const body = await request.json();
    const { subject, category, priority, message, attachments } = body;

    // Validation
    if (!subject || typeof subject !== "string" || subject.trim().length < 3) {
      return NextResponse.json(
        { error: "Subject is required and must be at least 3 characters" },
        { status: 400 },
      );
    }

    if (!category || !VALID_CATEGORIES.includes(category)) {
      return NextResponse.json(
        {
          error:
            "Invalid category. Must be one of: BILLING, TECHNICAL, FEATURE_REQUEST, OTHER",
        },
        { status: 400 },
      );
    }

    if (!message || typeof message !== "string" || message.trim().length < 10) {
      return NextResponse.json(
        { error: "Message is required and must be at least 10 characters" },
        { status: 400 },
      );
    }

    if (priority && !VALID_PRIORITIES.includes(priority)) {
      return NextResponse.json(
        { error: "Invalid priority. Must be one of: LOW, NORMAL, URGENT" },
        { status: 400 },
      );
    }

    // Validate attachments if provided
    if (
      attachments &&
      (!Array.isArray(attachments) ||
        attachments.some((a: unknown) => typeof a !== "string"))
    ) {
      return NextResponse.json(
        { error: "Attachments must be an array of strings (URLs)" },
        { status: 400 },
      );
    }

    const ticketId = await convexMutation("support/mutations:createTicket", {
      userId,
      subject,
      message: message ?? "",
      category,
      priority: priority ?? "NORMAL",
      attachments: attachments ?? undefined,
    });

    if (ticketId !== null) {
      return NextResponse.json(
        { ticket: { id: ticketId }, success: true },
        { status: 201 },
      );
    }

    return NextResponse.json(
      { error: "Ticket creation not available" },
      { status: 503 },
    );
  } catch (error) {
    logger.error("Failed to create ticket", { error });
    return NextResponse.json(
      { error: "Failed to create ticket" },
      { status: 500 },
    );
  }
}
