import { aggregateAcrossTeams, formatAggregationResult, loopGet, } from "../lib/loop-api.js";
export async function viewingSearch(params) {
    const { accountId, department = "both", searchTerm, appointmentStartDate, appointmentEndDate, status, teamName, limit, } = params;
    const result = await aggregateAcrossTeams(accountId, "viewings", "loop-viewing-search", async (apiKey, team) => {
        const depts = department === "both" ? ["sales", "lettings"] : [department];
        const all = [];
        for (const dept of depts) {
            const qp = [];
            if (searchTerm)
                qp.push(`SearchTerm=${encodeURIComponent(searchTerm)}`);
            if (appointmentStartDate)
                qp.push(`AppointmentStartDate=${encodeURIComponent(appointmentStartDate)}`);
            if (appointmentEndDate)
                qp.push(`AppointmentEndDate=${encodeURIComponent(appointmentEndDate)}`);
            if (status)
                qp.push(`Status=${encodeURIComponent(status)}`);
            const query = qp.length > 0 ? `?${qp.join("&")}` : "";
            const path = `/residential/${dept}/viewings${query}`;
            const data = await loopGet(apiKey, path, "loop-viewing-search", team);
            if (Array.isArray(data))
                all.push(...data);
        }
        return all;
    }, { teamName, limitPerTeam: limit ?? 50, limitTotal: limit ?? 200 });
    return formatAggregationResult(result, (v) => {
        const addr = v.propertyAddress ?? "Unknown property";
        const id = v.id != null ? ` [ID: ${v.id}]` : "";
        // dateOfAppointment is ISO datetime e.g. "2026-04-10T15:30:00"
        const when = v.dateOfAppointment
            ? formatDateTime(v.dateOfAppointment)
            : "No date";
        const viewStatus = v.status ? ` [${v.status}]` : "";
        const buyer = v.buyerName ? ` — ${v.buyerName}` : "";
        const viewType = v.type ? ` (${v.type})` : "";
        return `- ${addr}${id} — ${when}${viewType}${buyer}${viewStatus}`;
    }, "viewings");
}
function formatDateTime(iso) {
    const [datePart, timePart] = iso.split("T");
    if (!timePart)
        return datePart;
    return `${datePart} ${timePart.slice(0, 5)}`;
}
//# sourceMappingURL=viewing-search.js.map