/**
 * Broker Bulk Import API
 * POST /api/real-estate/brokers/import
 *   Accepts pre-parsed array of broker 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("BrokerBulkImportAPI");

export const dynamic = "force-dynamic";

const MAX_IMPORT = 50;

const TIME_RE = /^\d{2}:\d{2}$/;

interface ImportBrokerRow {
  nameEn?: string;
  nameAr?: string;
  phone?: string;
  email?: string;
  whatsappNumber?: string;
  licenseNumber?: string;
  workStartTime?: string;
  workEndTime?: string;
  maxViewingsPerDay?: number | 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 { brokers } = body as { brokers?: unknown[] };

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

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

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

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

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

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

      const workStartTime = row.workStartTime
        ? String(row.workStartTime).trim()
        : "09:00";
      if (!TIME_RE.test(workStartTime)) {
        errors.push(`${rowLabel}: workStartTime must be HH:MM format`);
        continue;
      }

      const workEndTime = row.workEndTime
        ? String(row.workEndTime).trim()
        : "18:00";
      if (!TIME_RE.test(workEndTime)) {
        errors.push(`${rowLabel}: workEndTime must be HH:MM format`);
        continue;
      }

      const maxViewingsPerDay = row.maxViewingsPerDay
        ? Number(row.maxViewingsPerDay)
        : 6;
      if (isNaN(maxViewingsPerDay) || maxViewingsPerDay < 1) {
        errors.push(`${rowLabel}: maxViewingsPerDay must be a positive number`);
        continue;
      }

      try {
        await convexMutation("real_estate/mutations:createBroker", {
          userId: user.userId,
          nameEn,
          nameAr: row.nameAr ? String(row.nameAr).trim() : undefined,
          phone,
          email: row.email ? String(row.email).trim() : undefined,
          whatsappNumber: row.whatsappNumber
            ? String(row.whatsappNumber).trim()
            : undefined,
          licenseNumber: row.licenseNumber
            ? String(row.licenseNumber).trim()
            : undefined,
          workStartTime,
          workEndTime,
          maxViewingsPerDay,
        });
        imported++;
      } catch (err) {
        errors.push(
          `${rowLabel}: failed to create - ${err instanceof Error ? err.message : "unknown error"}`,
        );
      }
    }

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

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

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