/**
 * Voice Agent Server Tool - Property Details
 *
 * POST /api/voice-agent/server-tools/property-details
 * Called by ElevenLabs during live conversations to get detailed property info
 * Auth: token-based via ?token= query param
 */

export const dynamic = "force-dynamic";

import { NextRequest, NextResponse } from "next/server";
import { prisma } from "@/lib/db";
import { logger } from "@/lib/logger";
import { getEffectiveOwnerId } from "@/lib/utils/organization-data";
import { getDataSource } from "@/lib/data-source";

const scopedLogger = logger.scope("VoiceAgentPropertyDetailsTool");

/**
 * Authenticate via token query parameter
 */
async function authenticateToken(request: NextRequest): Promise<string | null> {
  const token = request.nextUrl.searchParams.get("token");
  if (!token) return null;

  // ── Convex data-source branch ──────────────────────────────────────
  if (getDataSource("voice_agents") === "convex") {
    try {
      const { convexQuery } = await import("@/lib/convex-client");
      const cvxUser = (await convexQuery(
        "voice_agents/queries:getUserByWebhookToken",
        {
          token,
        },
      )) as { prismaId?: string; _id: string } | null;
      return cvxUser?.prismaId ?? cvxUser?._id ?? null;
    } catch (convexError) {
      console.error(
        "[Convex fallback] voice_agents property-details auth:",
        convexError,
      );
    }
  }

  const user = await prisma.users.findFirst({
    where: { n8nWebhookToken: token },
    select: { id: true },
  });

  return user?.id || null;
}

export async function POST(request: NextRequest) {
  try {
    const userId = await authenticateToken(request);
    if (!userId) {
      return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
    }

    const effectiveUserId = await getEffectiveOwnerId(userId);

    const body = await request.json();
    const referenceNumber =
      body.reference_number || body.parameters?.reference_number;
    const propertyId = body.property_id || body.parameters?.property_id;

    if (!referenceNumber && !propertyId) {
      return NextResponse.json({
        success: false,
        message:
          "Please provide either a property reference number or property ID to look up details.",
      });
    }

    scopedLogger.info("Property details requested", {
      userId,
      effectiveUserId,
      referenceNumber,
      propertyId,
    });

    // Build query: find by referenceNumber or ID, scoped to user
    const where: Record<string, unknown> = {
      userId: effectiveUserId,
    };

    if (referenceNumber) {
      where.referenceNumber = referenceNumber;
    } else if (propertyId) {
      where.id = propertyId;
    }

    const property = await prisma.property.findFirst({
      where,
      include: {
        images: {
          take: 3,
          orderBy: { sortOrder: "asc" },
          select: { url: true, isPrimary: true },
        },
        listingBroker: {
          select: { nameEn: true, phone: true },
        },
      },
    });

    if (!property) {
      return NextResponse.json({
        success: false,
        message:
          "I could not find a property with that reference. Could you please double-check and try again?",
      });
    }

    // Parse amenities from JSON
    let amenitiesList: string[] = [];
    try {
      const raw = property.amenities;
      if (Array.isArray(raw)) {
        amenitiesList = raw.slice(0, 5).map(String);
      } else if (typeof raw === "string") {
        amenitiesList = JSON.parse(raw).slice(0, 5);
      }
    } catch {
      // amenities parsing failed, continue without them
    }

    // Build detailed natural language response
    const parts: string[] = [];

    // Basic info
    parts.push(
      `${property.titleEn} is a ${property.propertyType.toLowerCase().replace(/_/g, " ")} listed for ${property.listingType.toLowerCase()}.`,
    );

    // Specs
    const specs: string[] = [];
    if (property.bedrooms) specs.push(`${property.bedrooms} bedrooms`);
    if (property.bathrooms) specs.push(`${property.bathrooms} bathrooms`);
    if (property.builtUpArea)
      specs.push(`${property.builtUpArea} square meters`);
    if (specs.length > 0) {
      parts.push(`It features ${specs.join(", ")}.`);
    }

    // Price
    parts.push(
      `The price is ${property.currency} ${property.price.toLocaleString()}.`,
    );

    // Location
    const locationParts: string[] = [];
    if (property.district) locationParts.push(property.district);
    if (property.city) locationParts.push(property.city);
    if (property.buildingName) locationParts.push(property.buildingName);
    if (property.unitNumber) locationParts.push(`Unit ${property.unitNumber}`);
    if (locationParts.length > 0) {
      parts.push(`Location: ${locationParts.join(", ")}.`);
    }

    // Additional details
    const details: string[] = [];
    if (property.furnishing) {
      details.push(
        `Furnishing: ${property.furnishing.toLowerCase().replace(/_/g, " ")}`,
      );
    }
    if (property.ownership) {
      details.push(
        `Ownership: ${property.ownership.toLowerCase().replace(/_/g, " ")}`,
      );
    }
    if (property.parkingSpaces) {
      details.push(`Parking: ${property.parkingSpaces} spaces`);
    }
    if (property.yearBuilt) {
      details.push(`Year built: ${property.yearBuilt}`);
    }
    if (details.length > 0) {
      parts.push(details.join(". ") + ".");
    }

    // Amenities
    if (amenitiesList.length > 0) {
      parts.push(`Key amenities include: ${amenitiesList.join(", ")}.`);
    }

    // Broker info
    if (property.listingBroker) {
      parts.push(
        `The listing broker is ${property.listingBroker.nameEn}${property.listingBroker.phone ? `, reachable at ${property.listingBroker.phone}` : ""}.`,
      );
    }

    parts.push("Would you like to schedule a viewing?");

    const message = parts.join(" ");

    scopedLogger.info("Property details returned", {
      userId,
      propertyId: property.id,
    });

    return NextResponse.json({
      success: true,
      message,
      property: {
        id: property.id,
        titleEn: property.titleEn,
        titleAr: property.titleAr,
        propertyType: property.propertyType,
        listingType: property.listingType,
        bedrooms: property.bedrooms,
        bathrooms: property.bathrooms,
        builtUpArea: property.builtUpArea,
        price: property.price,
        currency: property.currency,
        district: property.district,
        city: property.city,
        buildingName: property.buildingName,
        unitNumber: property.unitNumber,
        furnishing: property.furnishing,
        ownership: property.ownership,
        parkingSpaces: property.parkingSpaces,
        yearBuilt: property.yearBuilt,
        amenities: amenitiesList,
        referenceNumber: property.referenceNumber,
        images: property.images,
        listingBroker: property.listingBroker,
      },
    });
  } catch (error) {
    scopedLogger.error("Error in property details tool", error);
    return NextResponse.json(
      {
        success: false,
        message:
          "Sorry, I could not retrieve property details right now. Please try again.",
      },
      { status: 500 },
    );
  }
}
