import { NextRequest, NextResponse } from "next/server";
import { logger } from "@/lib/logger";
import { createClient, getSupabaseAdmin } from "@/lib/supabase/server";
import { sendEmail } from "@/lib/email";
import { checkRateLimit, getClientIP, createRateLimitResponse } from "@/lib/rate-limit";
import { HTTP_STATUS_INTERNAL_SERVER_ERROR } from "@/lib/constants";
import { validateCSRFToken } from "@/lib/csrf";

// Rate limit: 3 reports per 15 minutes
const RATE_LIMIT = 3;
const WINDOW_MS = 15 * 60 * 1000;

export type IssueCategory = "payment" | "no_show" | "safety" | "quality" | "other";

const VALID_CATEGORIES: IssueCategory[] = ["payment", "no_show", "safety", "quality", "other"];

/**
 * POST /api/issues/report
 *
 * Report an issue (payment, safety, no-show, etc.)
 * Stores in DB and sends email notification to admin.
 */
export async function POST(request: NextRequest) {
  try {
    // CSRF check
    const csrfValid = await validateCSRFToken(request);
    if (!csrfValid) {
      return NextResponse.json({ error: "Invalid CSRF token" }, { status: 403 });
    }

    const clientIP = getClientIP(request);
    const rateLimit = await checkRateLimit(`issue-report:${clientIP}`, RATE_LIMIT, WINDOW_MS);
    if (!rateLimit.allowed) {
      const retryAfter = Math.ceil((rateLimit.resetTime - Date.now()) / 1000);
      return createRateLimitResponse(clientIP, retryAfter);
    }

    const supabase = await createClient();
    const {
      data: { user },
    } = await supabase.auth.getUser();
    if (!user) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }

    const body = await request.json();
    const { category, match_id, description } = body;

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

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

    const admin = getSupabaseAdmin();

    // Store the issue report
    const { data: issue, error: insertError } = await admin
      .from("issue_reports")
      .insert({
        reporter_id: user.id,
        category,
        match_id: match_id || null,
        description: description.trim().slice(0, 2000),
        status: "open",
      })
      .select("id")
      .single();

    if (insertError) {
      logger.error("Failed to insert issue report:", insertError);
      return NextResponse.json({ error: "Failed to submit report" }, { status: HTTP_STATUS_INTERNAL_SERVER_ERROR });
    }

    // Get reporter info
    const { data: reporter } = await admin
      .from("profiles")
      .select("name, email, phone")
      .eq("id", user.id)
      .single();

    // Email notification to admin (fire-and-forget)
    const priorityLabel = category === "safety" ? "🚨 URGENT" : "📋";
    const subject = `${priorityLabel} Issue Report: ${category.replace("_", " ")} — ${reporter?.name || "User"}`;
    const html = `
      <h2>${priorityLabel} Issue Report</h2>
      <p><strong>Category:</strong> ${category.replace("_", " ")}</p>
      <p><strong>Reporter:</strong> ${reporter?.name || "Unknown"} (${reporter?.email || user.email})</p>
      <p><strong>Phone:</strong> ${reporter?.phone || "Not provided"}</p>
      ${match_id ? `<p><strong>Match ID:</strong> ${match_id}</p>` : ""}
      <p><strong>Description:</strong></p>
      <p>${description.trim()}</p>
      <hr/>
      <p><small>Report ID: ${issue.id} | ${new Date().toLocaleString("en-AU", { timeZone: "Australia/Sydney" })}</small></p>
    `;

    sendEmail("support@rateright.com.au", subject, html).catch((err) =>
      logger.error("Issue report email failed:", err)
    );

    return NextResponse.json({ success: true, id: issue.id });
  } catch (error) {
    logger.error("Issue report error:", error);
    return NextResponse.json({ error: "Failed to submit report" }, { status: HTTP_STATUS_INTERNAL_SERVER_ERROR });
  }
}
