/**
 * Real Estate Broker Assignment Service
 * Assigns the best available broker for a viewing based on availability and specialization.
 */

import { prisma } from "@/lib/db";
import { logger } from "@/lib/logger";

interface AssignmentRequest {
  requestedDate: Date;
  requestedTime: string;
  preferredLanguage?: string;
}

interface BrokerInfo {
  id: string;
  nameEn: string;
  nameAr: string | null;
  phone: string;
  email: string | null;
}

interface AssignmentResult {
  broker: BrokerInfo | null;
  reason: string;
}

export class BrokerAssignmentService {
  static async assignBroker(
    userId: string,
    propertyId: string,
    request: AssignmentRequest,
  ): Promise<AssignmentResult> {
    try {
      // Find available brokers for this user/org
      const brokers = await prisma.broker.findMany({
        where: {
          userId,
          isActive: true,
        },
        orderBy: { createdAt: "asc" },
      });

      if (brokers.length === 0) {
        return { broker: null, reason: "No brokers available" };
      }

      // Simple round-robin: pick the first active broker
      // In future, this should consider workload, specialization, language, etc.
      const selectedBroker = brokers[0];

      logger.info("Broker assigned", {
        brokerId: selectedBroker.id,
        propertyId,
        userId,
      });

      return {
        broker: {
          id: selectedBroker.id,
          nameEn: selectedBroker.nameEn,
          nameAr: selectedBroker.nameAr,
          phone: selectedBroker.phone,
          email: selectedBroker.email,
        },
        reason: "Auto-assigned (round-robin)",
      };
    } catch (error) {
      logger.error("Broker assignment failed", { error, userId, propertyId });
      return { broker: null, reason: "Assignment failed" };
    }
  }
}
