import { render, screen, waitFor } from "@testing-library/react"
import { API } from "@/api/API"
import { FinanceFnFDetailsPage } from "../pages/FinanceFnFDetailsPage"

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

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

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

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

jest.mock("@/services/settlement.service", () => ({
    settlementService: {
        updateFnF: jest.fn(),
    },
}))

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

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

    it("shows not found when settlement cannot be loaded", async () => {
        jest.mocked(API.getFnFSettlementById).mockResolvedValue({
            data: { success: false },
        } as never)

        render(
            <FinanceFnFDetailsPage fnfId="bad-id" onBack={onBack} />,
        )

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

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

    it("fetches departments and settlement on mount", async () => {
        jest.mocked(API.getFnFSettlementById).mockResolvedValue({
            data: { success: false },
        } as never)

        render(<FinanceFnFDetailsPage fnfId="fnf-xyz" onBack={onBack} />)

        await waitFor(() => {
            expect(API.getSettlementDepartments).toHaveBeenCalled()
            expect(API.getFnFSettlementById).toHaveBeenCalledWith("fnf-xyz")
        })
    })
})
