/**
 * Tenant Issue Bulk Import API
 * POST /api/dashboard/tenant-issues/import
 *   Accepts pre-parsed array of tenant issue objects (frontend parses CSV).
 */

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 { convexMutation } from "@/lib/convex-client";
import { withCSRF } from "@/lib/csrf";
import { withRateLimit, rateLimiters } from "@/lib/rate-limiter";

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

export const dynamic = "force-dynamic";

const MAX_IMPORT = 100;

const VALID_CATEGORIES = [
  "plumbing",
  "electrical",
  "hvac",
  "structural",
  "appliance",
  "pest_control",
  "cleaning",
  "other",
];

const VALID_PRIORITIES = ["low", "medium", "high", "urgent"];

interface ImportIssueRow {
  propertyId?: string;
  title?: string;
  description?: string;
  category?: string;
  priority?: string;
  unit?: string;
  tenantName?: string;
}

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

    const body = await request.json();
    const { issues } = body as { issues?: unknown[] };

    if (!Array.isArray(issues) || issues.length === 0) {
      return NextResponse.json(
        { success: false, error: "issues must be a non-empty array" },
        { status: 400 },
      );
    }

    if (issues.length > MAX_IMPORT) {
      return NextResponse.json(
        {
          success: false,
          error: `Cannot import more than ${MAX_IMPORT} issues at once`,
        },
        { status: 400 },
      );
    }

    const errors: string[] = [];
    let imported = 0;

    for (let i = 0; i < issues.length; i++) {
      const row = issues[i] as ImportIssueRow;
      const rowLabel = `Row ${i + 1}`;

      const propertyId = row.propertyId ? String(row.propertyId).trim() : "";
      if (!propertyId) {
        errors.push(`${rowLabel}: propertyId is required`);
        continue;
      }

      const title = row.title ? String(row.title).trim() : "";
      if (!title) {
        errors.push(`${rowLabel}: title is required`);
        continue;
      }

      const category = row.category
        ? String(row.category).trim().toLowerCase()
        : "other";
      if (!VALID_CATEGORIES.includes(category)) {
        errors.push(
          `${rowLabel}: invalid category "${row.category}". Valid: ${VALID_CATEGORIES.join(", ")}`,
        );
        continue;
      }

      const priority = row.priority
        ? String(row.priority).trim().toLowerCase()
        : "medium";
      if (!VALID_PRIORITIES.includes(priority)) {
        errors.push(
          `${rowLabel}: invalid priority "${row.priority}". Valid: ${VALID_PRIORITIES.join(", ")}`,
        );
        continue;
      }

      try {
        await convexMutation("real_estate/mutations:createTenantIssue", {
          userId: user.userId,
          propertyId,
          title,
          description: row.description
            ? String(row.description).trim()
            : undefined,
          category,
          priority,
          unit: row.unit ? String(row.unit).trim() : undefined,
          tenantName: row.tenantName
            ? String(row.tenantName).trim()
            : undefined,
        });
        imported++;
      } catch (err) {
        errors.push(
          `${rowLabel}: failed to create - ${err instanceof Error ? err.message : "unknown error"}`,
        );
      }
    }

    log.info("Tenant issue bulk import completed", {
      userId: user.userId,
      requested: issues.length,
      imported,
      errorCount: errors.length,
    });

    return NextResponse.json({ success: true, imported, errors });
  } catch (error) {
    log.error("Failed to bulk import tenant issues", error);
    return NextResponse.json(
      { success: false, error: "Internal server error" },
      { status: 500 },
    );
  }
}

export const POST = withRateLimit(
  withCSRF(postHandler),
  rateLimiters.authGeneral,
);
