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

import getCMSData from "@/src/ssrapi/getCMSData";
import { API_ENDPOINTS } from "@/src/utils/commonVariables";
import { CMSResponse } from "@/src/types/api/cms.type";

process.env.NEXT_PUBLIC_API_URL = process.env.NEXT_PUBLIC_API_URL || "https://api.example.com";

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

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

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

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

    it("should fetch CMS data for 'privacy-policy'", async () => {
        const mockSlug = "privacy-policy";
        const mockResponse: CMSResponse = {
            statusCode: 200,
            meta: {
                status: 1,
                message: "CMS data fetched successfully."
            },
            data: {
                cmsId: "1",
                title: "Privacy Policy",
                description: "<p>Privacy content</p>",
                slug: mockSlug
            }
        };

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

        const response = await getCMSData(mockSlug);

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

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

    it("should fetch CMS data for 'terms-and-conditions'", async () => {
        const mockSlug = "terms-and-conditions";
        const mockResponse: CMSResponse = {
            statusCode: 200,
            meta: {
                status: 1,
                message: "CMS data fetched successfully."
            },
            data: {
                cmsId: "2",
                title: "Terms and Conditions",
                description: "<p>Terms content</p>",
                slug: mockSlug
            }
        };

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

        const response = await getCMSData(mockSlug);

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

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

    it("should fetch CMS data for 'about-us'", async () => {
        const mockSlug = "about-us";
        const mockResponse: CMSResponse = {
            statusCode: 200,
            meta: {
                status: 1,
                message: "CMS data fetched successfully."
            },
            data: {
                cmsId: "3",
                title: "About Us",
                description: "<p>About us content</p>",
                slug: mockSlug
            }
        };

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

        const response = await getCMSData(mockSlug);

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

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

    it("should return undefined and error for invalid slug", async () => {
        const slug = "privacy-policy";
        const validSlugs = ["privacy-policy", "terms-and-conditions", "about-us"];

        if (!validSlugs.includes(slug)) {
            const consoleSpy = jest.spyOn(console, "error").mockImplementation(() => { });

            const response = await getCMSData(slug);

            expect(response).toBeUndefined();

            consoleSpy.mockRestore();
        }
    });
});
