import { render, screen, waitFor } from "@testing-library/react"
import { MemoryRouter } from "react-router-dom"
import { API } from "@/api/API"
import { MEMORY_ROUTER_TEST_FUTURE } from "@/testing/reactRouterTest"
import { FnFDetails } from "../pages/FnFDetails"

jest.mock("sonner", () => ({
    toast: {
        error: jest.fn(),
        success: jest.fn(),
    },
}))

jest.mock("@/api/API", () => ({
    API: {
        getFnFSettlementById: jest.fn(),
        getAuditLogs: jest.fn().mockResolvedValue({
            data: { success: true, data: [] },
        }),
        getDealerBankDetails: jest.fn(),
    },
}))

jest.mock("@/components/ui/DocumentPreviewModal", () => ({
    DocumentPreviewModal: () => null,
}))

jest.mock("@/features/onboarding/components/BankDetailsModal", () => ({
    BankDetailsModal: () => null,
}))

describe("FnFDetails", () => {
    const onBack = jest.fn()

    beforeEach(() => {
        jest.clearAllMocks()
    })

    function setup(fnfId = "missing-id") {
        render(
            <MemoryRouter future={MEMORY_ROUTER_TEST_FUTURE}>
                <FnFDetails
                    fnfId={fnfId}
                    onBack={onBack}
                    currentUser={{ role: "DD Lead", name: "Lead" }}
                />
            </MemoryRouter>,
        )
    }

    it("shows case not found when API returns unsuccessful payload", async () => {
        jest.mocked(API.getFnFSettlementById).mockResolvedValue({
            data: { success: false },
        } as never)

        setup()

        expect(
            await screen.findByText(/case not found/i),
        ).toBeInTheDocument()

        screen.getByRole("button", { name: /^go back$/i }).click()
        expect(onBack).toHaveBeenCalled()
    })

    it("requested settlement by id", async () => {
        jest.mocked(API.getFnFSettlementById).mockResolvedValue({
            data: { success: false },
        } as never)

        setup("fnf-uuid-123")

        await waitFor(() => {
            expect(API.getFnFSettlementById).toHaveBeenCalledWith(
                "fnf-uuid-123",
            )
        })
    })
})
