/**
 * Tenant Issues API — List and Create
 * GET  /api/dashboard/tenant-issues - List tenant issues for the user
 * POST /api/dashboard/tenant-issues - Create a new tenant issue
 */

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 { convexQuery, convexMutation } from "@/lib/convex-client";
import { validateCSRFToken } from "@/lib/csrf";

const log = logger.scope("TenantIssuesAPI");

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

export async function GET(request: NextRequest) {
  try {
    const user = await getAuthenticatedUser(request, auth);
    if (!user) {
      return NextResponse.json(
        { success: false, error: "Unauthorized" },
        { status: 401 },
      );
    }

    const propertyId =
      request.nextUrl.searchParams.get("propertyId") || undefined;
    const status = request.nextUrl.searchParams.get("status") || undefined;
    const priority = request.nextUrl.searchParams.get("priority") || undefined;

    const issues = await convexQuery("real_estate/queries:getTenantIssues", {
      userId: user.userId,
      propertyId,
      status,
      priority,
    });

    return NextResponse.json({
      success: true,
      issues: issues ?? [],
    });
  } catch (error) {
    log.error("Failed to list tenant issues", error);
    return NextResponse.json(
      { success: false, error: "Internal server error" },
      { status: 500 },
    );
  }
}

export async function POST(request: NextRequest) {
  try {
    if (!validateCSRFToken(request)) {
      return NextResponse.json(
        { success: false, error: "Invalid CSRF token" },
        { status: 403 },
      );
    }

    const user = await getAuthenticatedUser(request, auth);
    if (!user) {
      return NextResponse.json(
        { success: false, error: "Unauthorized" },
        { status: 401 },
      );
    }

    const body = await request.json();
    const { title, description, category, priority, propertyId, unit, tenantName } = body;

    if (!title?.trim()) {
      return NextResponse.json(
        { success: false, error: "Title is required" },
        { status: 400 },
      );
    }

    if (!propertyId?.trim()) {
      return NextResponse.json(
        { success: false, error: "Property is required" },
        { status: 400 },
      );
    }

    const id = await convexMutation(
      "real_estate/mutations:createTenantIssue",
      {
        userId: user.userId,
        propertyId,
        title: title.trim(),
        description: description?.trim() || undefined,
        category: category || "other",
        priority: priority || "medium",
        unit: unit?.trim() || undefined,
        tenantName: tenantName?.trim() || undefined,
      },
    );

    // Fetch the created issue to return full data
    const issues = (await convexQuery("real_estate/queries:getTenantIssues", {
      userId: user.userId,
    })) as Array<Record<string, unknown>> | null;
    const created = issues?.find(
      (i) => i._id === id || i.id === id,
    );

    return NextResponse.json(created ?? { id, success: true }, { status: 201 });
  } catch (error) {
    log.error("Failed to create tenant issue", error);
    return NextResponse.json(
      { success: false, error: "Internal server error" },
      { status: 500 },
    );
  }
}
