/**
 * Real Estate Brokers API
 * GET  - List active brokers for the organization with stats
 * POST - Create a new broker profile
 */

import { NextRequest } from "next/server";
import { auth } from "@/lib/auth";
import { prisma } from "@/lib/db";
import { getAuthenticatedEmail } from "@/lib/utils/auth-helpers.util";
import { getEffectiveOwnerId } from "@/lib/utils/organization-data";
import { logger } from "@/lib/logger";
import { createId } from "@paralleldrive/cuid2";
import { ApiResponses } from "@/lib/utils/api-response.util";
import { withRateLimit, rateLimiters } from "@/lib/rate-limiter";
import { getErrorMessage } from "@/lib/errors";
import { withCSRF } from "@/lib/csrf";

export const dynamic = "force-dynamic";

/**
 * GET /api/real-estate/brokers
 * List active brokers for the org. Include stats (totalViewings, totalClosings).
 */
export const GET = withRateLimit(async (request: NextRequest) => {
  try {
    const userEmail = await getAuthenticatedEmail(request, auth);
    if (!userEmail) {
      return ApiResponses.unauthorized();
    }

    const user = await prisma.users.findUnique({
      where: { email: userEmail },
      select: { id: true },
    });
    if (!user) {
      return ApiResponses.notFound("User not found");
    }

    const effectiveUserId = await getEffectiveOwnerId(user.id);

    const brokers = await prisma.broker.findMany({
      where: { userId: effectiveUserId, isActive: true },
      orderBy: { createdAt: "desc" },
    });

    return ApiResponses.success({ brokers });
  } catch (error) {
    logger.error("[Brokers API] GET error", {
      error: getErrorMessage(error),
    });
    return ApiResponses.serverError("Failed to fetch brokers");
  }
}, rateLimiters.authGeneral);

/**
 * POST /api/real-estate/brokers
 * Create a new broker profile.
 */
export const POST = withRateLimit(
  withCSRF(async (request: NextRequest) => {
    try {
      const userEmail = await getAuthenticatedEmail(request, auth);
      if (!userEmail) {
        return ApiResponses.unauthorized();
      }

      const user = await prisma.users.findUnique({
        where: { email: userEmail },
        select: { id: true },
      });
      if (!user) {
        return ApiResponses.notFound("User not found");
      }

      const effectiveUserId = await getEffectiveOwnerId(user.id);
      const body = await request.json();

      // Validate required fields
      if (
        !body.nameEn ||
        typeof body.nameEn !== "string" ||
        body.nameEn.trim().length === 0
      ) {
        return ApiResponses.badRequest("nameEn is required");
      }
      if (
        !body.phone ||
        typeof body.phone !== "string" ||
        body.phone.trim().length === 0
      ) {
        return ApiResponses.badRequest("phone is required");
      }

      // Look up organizationId for this user
      const membership = await prisma.organization_members.findFirst({
        where: { userId: user.id },
        select: { organizationId: true },
      });

      const broker = await prisma.broker.create({
        data: {
          id: createId(),
          userId: effectiveUserId,
          organizationId: membership?.organizationId || null,
          nameEn: body.nameEn.trim(),
          nameAr: body.nameAr?.trim() || null,
          phone: body.phone.trim(),
          email: body.email?.trim() || null,
          whatsappNumber: body.whatsappNumber?.trim() || null,
          languages: body.languages || ["en", "ar"],
          areaSpecializations: body.areaSpecializations || [],
          typeSpecializations: body.typeSpecializations || [],
          workingDays: body.workingDays || [0, 1, 2, 3, 4],
          workStartTime: body.workStartTime || "09:00",
          workEndTime: body.workEndTime || "18:00",
          maxViewingsPerDay: body.maxViewingsPerDay || 6,
        },
      });

      logger.info("[Brokers API] Broker created", {
        brokerId: broker.id,
        userId: effectiveUserId,
      });

      return ApiResponses.success({ broker });
    } catch (error) {
      logger.error("[Brokers API] POST error", {
        error: getErrorMessage(error),
      });
      return ApiResponses.serverError("Failed to create broker");
    }
  }),
  rateLimiters.authGeneral,
);
