/**
 * Property Bulk Import API
 * POST /api/real-estate/properties/import
 *   Accepts pre-parsed array of property 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("PropertyBulkImportAPI");

export const dynamic = "force-dynamic";

const MAX_IMPORT = 100;

const VALID_PROPERTY_TYPES = [
  "APARTMENT",
  "VILLA",
  "TOWNHOUSE",
  "PENTHOUSE",
  "DUPLEX",
  "STUDIO",
  "COMPOUND_VILLA",
  "OFFICE",
  "RETAIL",
  "WAREHOUSE",
  "SHOWROOM",
  "LAND_RESIDENTIAL",
  "LAND_COMMERCIAL",
  "HOTEL_APARTMENT",
  "SERVICED_APARTMENT",
];

const VALID_LISTING_TYPES = ["SALE", "RENT"];
const VALID_CURRENCIES = ["QAR", "SAR", "AED", "KWD", "BHD", "OMR"];

interface ImportPropertyRow {
  titleEn?: string;
  titleAr?: string;
  propertyType?: string;
  listingType?: string;
  city?: string;
  district?: string;
  price?: number | string;
  currency?: string;
  bedrooms?: number | string;
  bathrooms?: number | string;
  builtUpArea?: number | string;
  furnishing?: string;
  ownership?: 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 { properties } = body as { properties?: unknown[] };

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

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

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

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

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

      const propertyType = row.propertyType
        ? String(row.propertyType).trim().toUpperCase()
        : "";
      if (!VALID_PROPERTY_TYPES.includes(propertyType)) {
        errors.push(
          `${rowLabel}: invalid propertyType "${row.propertyType}". Valid: ${VALID_PROPERTY_TYPES.join(", ")}`,
        );
        continue;
      }

      const listingType = row.listingType
        ? String(row.listingType).trim().toUpperCase()
        : "";
      if (!VALID_LISTING_TYPES.includes(listingType)) {
        errors.push(
          `${rowLabel}: listingType must be SALE or RENT`,
        );
        continue;
      }

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

      const price = Number(row.price);
      if (!row.price || isNaN(price) || price <= 0) {
        errors.push(`${rowLabel}: price must be a positive number`);
        continue;
      }

      const currency = row.currency
        ? String(row.currency).trim().toUpperCase()
        : "QAR";
      if (!VALID_CURRENCIES.includes(currency)) {
        errors.push(
          `${rowLabel}: invalid currency "${row.currency}". Valid: ${VALID_CURRENCIES.join(", ")}`,
        );
        continue;
      }

      const bedrooms = row.bedrooms !== undefined && row.bedrooms !== ""
        ? Number(row.bedrooms)
        : undefined;
      const bathrooms = row.bathrooms !== undefined && row.bathrooms !== ""
        ? Number(row.bathrooms)
        : undefined;
      const builtUpArea = row.builtUpArea !== undefined && row.builtUpArea !== ""
        ? Number(row.builtUpArea)
        : undefined;

      try {
        await convexMutation("real_estate/mutations:createProperty", {
          userId: user.userId,
          titleEn,
          titleAr: row.titleAr ? String(row.titleAr).trim() : undefined,
          propertyType,
          listingType,
          city,
          district: row.district ? String(row.district).trim() : undefined,
          price,
          currency,
          bedrooms,
          bathrooms,
          builtUpArea,
        });
        imported++;
      } catch (err) {
        errors.push(
          `${rowLabel}: failed to create - ${err instanceof Error ? err.message : "unknown error"}`,
        );
      }
    }

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

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

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