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 type { User } from "@/lib/mock-data"
import { RelocationRequestDetails } from "../pages/RelocationRequestDetails"

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

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

jest.mock("@/api/API", () => ({
    API: {
        getRelocationRequestById: jest.fn(),
        getAuditLogs: jest.fn().mockResolvedValue({
            data: { success: true, data: [] },
        }),
        getEorChecklistForRelocation: jest.fn(),
        updateEorChecklistItem: jest.fn(),
        submitEorAudit: jest.fn(),
        updateRelocationRequest: jest.fn(),
        uploadRelocationDocument: jest.fn(),
    },
}))

function staffUser(): User {
    return {
        id: "staff-1",
        name: "Reviewer",
        email: "r@test.com",
        password: "",
        role: "ASM",
    }
}

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

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

    function setup(requestId = "bad-id", user: User | null = staffUser()) {
        render(
            <MemoryRouter future={MEMORY_ROUTER_TEST_FUTURE}>
                <RelocationRequestDetails
                    requestId={requestId}
                    onBack={onBack}
                    currentUser={user}
                />
            </MemoryRouter>,
        )
    }

    it("shows not found when API does not return a request", async () => {
        jest.mocked(API.getRelocationRequestById).mockResolvedValue({
            data: { success: false },
        } as never)

        setup()

        expect(
            await screen.findByRole("heading", { name: /request not found/i }),
        ).toBeInTheDocument()

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

    it("loads details using requestId", async () => {
        jest.mocked(API.getRelocationRequestById).mockResolvedValue({
            data: { success: false },
        } as never)

        setup("reloc-uuid-99")

        await waitFor(() => {
            expect(API.getRelocationRequestById).toHaveBeenCalledWith(
                "reloc-uuid-99",
            )
        })
    })
})
