/**
 * @author: Hemal
 * File: getPropertyDetails.test.ts
 * Purpose: Unit tests for the `getPropertyDetails` API function.
 * Description:
 * - Mocks the `fetch` function using Jest.
 * - Validates correct API call and response handling for valid slugs.
 * - Returns `undefined` for fetch errors or invalid input.
 */

import getPropertyDetails from "@/src/ssrapi/getPropertyDetails";
import { API_ENDPOINTS } from "@/src/utils/commonVariables";
import { PropertyResponse } from "@/src/types/api/property.type";

describe("getPropertyDetails", () => {
    const originalFetch = global.fetch;

    beforeEach(() => {
        global.fetch = jest.fn();
    });

    afterEach(() => {
        jest.resetAllMocks();
    });

    afterAll(() => {
        global.fetch = originalFetch;
    });

    // Test case: fetch property details with valid slug
    it("should fetch property details for 'luxury-villa-dubai'", async () => {
        const mockSlug = "luxury-villa-dubai";
        const mockPropertyResponse: PropertyResponse = {
            statusCode: 200,
            meta: {
                status: 1,
                message: "Property details fetched successfully."
            },
            data: {
                propertyId: "prop-001",
                userId: "user-001",
                isVerified: true,
                propertyLocation: {
                    zip: "12345",
                    city: "Dubai",
                    state: "Dubai",
                    countryId: "AE",
                    streetName: "Palm Jumeirah",
                    countryData: {
                        countryId: "AE",
                        name: "United Arab Emirates",
                        sortCode: "UAE",
                        timezone: ["Asia/Dubai"],
                        capital: "Abu Dhabi",
                        currency: "AED",
                        flagImage: "https://example.com/uae-flag.png",
                        status: 1
                    }
                },
                name: "Luxury Beachfront Villa",
                slug: "luxury-beachfront-villa",
                headline: "Stunning Villa with Private Beach",
                currencySymbol: "د.إ",
                propertyType: "villa",
                propertyTypeData: {
                    propertyTypeId: "villa-001",
                    title: "Villa",
                    slug: "villa",
                    description: "Private luxury villa",
                    icon: "https://example.com/icons/villa.svg",
                    selectedIcon: "https://example.com/icons/villa-selected.svg",
                    listingIcon: "https://example.com/icons/villa-listing.svg"
                },
                totalGuests: 8,
                workspaceId: ["ws-123"],
                workspaceIsIn: "Living Room",
                workspaceType: "Dedicated",
                workspaceData: [
                    {
                        amenitiesId: "am-001",
                        title: "High-Speed WiFi",
                        slug: "high-speed-wifi",
                        icon: "https://example.com/icons/wifi.svg"
                    }
                ],
                workspaceIsInData: {
                    amenitiesId: "am-002",
                    title: "Work Desk",
                    slug: "work-desk",
                    icon: "https://example.com/icons/desk.svg"
                },
                workspaceImage: {
                    imageId: "img-ws-01",
                    imageUrl: "https://example.com/images/workspace.jpg"
                },
                propertyImage: [
                    {
                        imageId: "img-001",
                        imageUrl: "https://example.com/images/property-1.jpg"
                    },
                    {
                        imageId: "img-002",
                        imageUrl: "https://example.com/images/property-2.jpg"
                    }
                ],
                internet: "Fiber",
                internetInfo: {
                    ping: "5ms",
                    jitter: "1ms",
                    uploadSpeed: "500Mbps",
                    downloadSpeed: "1Gbps"
                },
                minimumStay: { number: 2, duration: "nights" },
                maximumStay: { number: 30, duration: "nights" },
                coordinates: {
                    crs: { type: "name", properties: { name: "EPSG:4326" } },
                    type: "Point",
                    coordinates: [55.1389, 25.0773]
                },
                propertyStatus: "active",
                needsModification: false,
                modificationReason: "",
                isBanned: false,
                banReason: "",
                isDetailsComplete: true,
                savedAsDraft: false,
                step: 4,
                substep: 2,
                createdAt: "2023-06-10T09:00:00Z",
                updatedAt: "2023-07-01T10:00:00Z",
                hostDetails: {
                    userId: "host-001",
                    firstName: "Ali",
                    lastName: "Khan",
                    email: "ali.khan@example.com",
                    profilePicture: {
                        imageId: "host-img-001",
                        imageUrl: "https://example.com/host/ali.jpg"
                    },
                    status: 1
                },
                totalPrice: "3000",
                price: 3000,
                currency: "AED",
                status: 1,
                bedrooms: [
                    {
                        bedType: [
                            { type: "King", count: 1 },
                            { type: "Twin", count: 2 }
                        ]
                    }
                ],
                bathrooms: [
                    {
                        other: ["Hot tub", "Bathtub"],
                        amenitiesId: ["am-bath-001", "am-bath-002"]
                    }
                ],
                additionalSleepSpace: {
                    number: 1,
                    roomType: "Guest Room",
                    spaceType: "Foldable Sofa"
                },
                totalBedrooms: 3,
                totalBathrooms: 2,
                totalBeds: 4,
                description: "A beautiful villa perfect for beach lovers and families.",
                checkIn: "15:00",
                checkOut: "11:00",
                anytimeCheckIn: false,
                anytimeCheckOut: false,
                isLateCheckOutAllowed: true,
                lateCheckout: "13:00",
                smoking: false,
                pet: true,
                children: true,
                notesForGuest: "Please keep the noise down after 10 PM.",
                houseRules: "No parties or events.",
                cancellationPolicy: "Moderate",
                deposit: { amount: 500, currency: "AED", currencySymbol: "د.إ" },
                negotiable: true,
                cleaningFee: { type: "Cleaning", price: 100, currency: "AED", currencySymbol: "د.إ" },
                petFee: { type: "Pet", price: 50, currency: "AED", currencySymbol: "د.إ" },
                serviceFee: { type: "Service", price: 75, currency: "AED", currencySymbol: "د.إ" },
                hasAcceptedTermsAndConditions: true,
                latestBeforeCheckin: { number: 1, duration: "day" },
                earliestBeforeCheckin: { number: 7, duration: "days" },
                blockDates: ["2023-12-25", "2024-01-01"],
                rentingType: "entire-place"
            }
        };

        (global.fetch as jest.Mock).mockResolvedValueOnce({
            json: jest.fn().mockResolvedValueOnce(mockPropertyResponse)
        });

        const response = await getPropertyDetails(mockSlug);

        expect(global.fetch).toHaveBeenCalledWith(
            `${process.env.NEXT_PUBLIC_API_URL}${API_ENDPOINTS.PROPERTY_DETAILS}`,
            {
                method: "POST",
                body: JSON.stringify({ slug: mockSlug }),
                headers: {
                    "Content-Type": "application/json",
                    "usertype": "guest"
                },
                cache: "no-store"
            }
        );

        expect(response).toEqual(mockPropertyResponse);
    });

    // Test case: return undefined on fetch error
    it("should return undefined on fetch error", async () => {
        const slug = "luxury-villa-dubai";

        (global.fetch as jest.Mock).mockRejectedValueOnce(new Error("Network error"));

        const response = await getPropertyDetails(slug);

        expect(response).toBeUndefined();
    });

    // Optional: Test invalid input (if handled in future logic)
    it("should return undefined for invalid property slug", async () => {
        const invalidSlug = "";

        // This test assumes no fetch call occurs if slug is empty or invalid
        const response = await getPropertyDetails(invalidSlug);

        // Either skip fetch entirely or return early
        expect(global.fetch).toHaveBeenCalled(); // Adjust if you add early return
        expect(response).toBeUndefined();
    });
});
