/**
 * Support Ticket Messages API - User-facing
 *
 * GET /api/support/tickets/[id]/messages - Get messages for a ticket
 * POST /api/support/tickets/[id]/messages - Add a reply to a ticket
 *
 * Convex-first with Prisma fallback.
 */

import { NextRequest, NextResponse } from "next/server";
import { auth } from "@/lib/auth";
import { getAuthenticatedUser } from "@/lib/utils/auth-helpers.util";
import { logger } from "@/lib/logger";
import { convexQueryStrict, convexMutation } from "@/lib/convex-client";

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

/**
 * GET /api/support/tickets/[id]/messages
 * Get messages for a ticket thread
 */
export async function GET(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> },
) {
  try {
    const authedUser = await getAuthenticatedUser(request, auth);
    if (!authedUser) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }

    const { id: ticketId } = await params;

    const result = (await convexQueryStrict(
      "support/queries:getTicketWithMessages",
      {
        ticketId,
      },
    )) as Record<string, unknown> | null;

    if (!result) {
      return NextResponse.json({ error: "Not found" }, { status: 404 });
    }

    // Verify user owns the ticket
    if (result.userId !== authedUser.userId) {
      return NextResponse.json({ error: "Not found" }, { status: 404 });
    }
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    const messages = ((result.messageThread ?? []) as any[]).map((m) => ({
      id: m._id ?? m.id,
      ticketId: m.ticketId,
      senderId: m.senderId,
      senderType: m.senderType,
      message: m.message,
      attachments: m.attachments,
      isRead: m.isRead,
      createdAt: m.createdAt ? new Date(m.createdAt).toISOString() : null,
    }));
    return NextResponse.json({ data: messages, success: true });
  } catch (error) {
    logger.error("Failed to fetch ticket messages", { error });
    return NextResponse.json(
      { error: "Failed to fetch messages" },
      { status: 500 },
    );
  }
}

/**
 * POST /api/support/tickets/[id]/messages
 * Add a user reply to a ticket thread
 */
export async function POST(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> },
) {
  try {
    const authedUser = await getAuthenticatedUser(request, auth);
    if (!authedUser) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }

    const { id: ticketId } = await params;

    if (!ticketId) {
      return NextResponse.json(
        { error: "Ticket ID is required" },
        { status: 400 },
      );
    }

    const body = await request.json();
    const { message, attachments } = body;

    // Validation
    if (!message || typeof message !== "string" || message.trim().length < 1) {
      return NextResponse.json(
        { error: "Message is required" },
        { status: 400 },
      );
    }

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

    // Convex-first: verify ticket ownership and status
    try {
      const ticket = (await convexQueryStrict(
        "support/queries:getTicketWithMessages",
        {
          ticketId,
        },
      )) as Record<string, unknown> | null;

      if (!ticket) {
        return NextResponse.json(
          { error: "Ticket not found" },
          { status: 404 },
        );
      }

      {
        // Verify user owns the ticket
        if (ticket.userId !== authedUser.userId) {
          return NextResponse.json(
            { error: "Ticket not found" },
            { status: 404 },
          );
        }
        if (ticket.status === "CLOSED") {
          return NextResponse.json(
            { error: "Cannot reply to a closed ticket" },
            { status: 400 },
          );
        }

        const messageId = await convexMutation("support/mutations:addMessage", {
          ticketId,
          senderId: authedUser.userId,
          senderType: "USER",
          message: message.trim(),
          attachments: attachments || undefined,
        });

        if (messageId !== null) {
          logger.info("User added message to ticket via Convex", {
            ticketId,
            userId: authedUser.userId,
            messageId,
          });

          return NextResponse.json(
            {
              message: {
                id: messageId,
                ticketId,
                senderId: authedUser.userId,
                senderType: "USER",
                message: message.trim(),
                attachments: attachments || [],
                isRead: false,
                createdAt: new Date().toISOString(),
              },
            },
            { status: 201 },
          );
        }
      }
    } catch (convexErr) {
      logger.error("Convex add message failed", { error: convexErr });
      return NextResponse.json(
        { error: "Failed to add message" },
        { status: 500 },
      );
    }

    // messageId was null — should not happen, but guard against it
    return NextResponse.json(
      { error: "Failed to add message" },
      { status: 500 },
    );
  } catch (error) {
    logger.error("Failed to add message", { error });
    return NextResponse.json(
      { error: "Failed to add message" },
      { status: 500 },
    );
  }
}
