import { fireEvent, render, screen, waitFor, within } from "@testing-library/react";
import { afterEach, expect, test, vi } from "vitest";
import { ToastProvider } from "@/shared/ui/ToastProvider.jsx";
import { FinanceApp } from "./FinanceApp.jsx";

vi.mock("./api.js", () => ({
  approveFinanceApplication: vi.fn(),
  approveFinanceWithdrawalApplication: vi.fn(),
  createFinanceApplication: vi.fn(),
  fetchFinanceApplicationOptions: vi.fn(async () => ({
    apps: [{ appCode: "lalu", appName: "lalu" }],
    operations: [{ label: "增加用户金币", permissionCode: "finance-operation:user-coin-credit", value: "user_coin_credit" }],
    walletIdentities: []
  })),
  fetchFinanceSession: vi.fn(async () => ({
    canAccessFinance: true,
    canAuditApplication: false,
    canCreateApplication: true,
    canViewAppRechargeDetails: false,
    canViewWithdrawalApplications: false,
    permissions: ["finance-application:create", "finance-operation:user-coin-credit"],
    user: { account: "admin", name: "admin" }
  })),
  filterOperationsByPermissions: vi.fn((operations, permissions) => operations.filter((item) => permissions.includes(item.permissionCode))),
  listFinanceApplications: vi.fn(),
  listFinanceRechargeDetails: vi.fn(),
  listFinanceWithdrawalApplications: vi.fn(),
  listMyFinanceApplications: vi.fn(async () => ({ items: [], page: 1, pageSize: 50, total: 0 })),
  rejectFinanceApplication: vi.fn(),
  rejectFinanceWithdrawalApplication: vi.fn()
}));

afterEach(() => {
  vi.clearAllMocks();
});

test("keeps create application dialog open when backdrop is clicked", async () => {
  render(
    <ToastProvider>
      <FinanceApp />
    </ToastProvider>
  );

  fireEvent.click(await screen.findByRole("button", { name: "添加" }));
  expect(within(screen.getByRole("dialog")).getByRole("heading", { name: "发起申请" })).toBeInTheDocument();

  const backdrop = document.querySelector(".MuiBackdrop-root");
  expect(backdrop).toBeTruthy();
  fireEvent.mouseDown(backdrop);
  fireEvent.click(backdrop);
  expect(screen.getByRole("dialog")).toBeInTheDocument();

  fireEvent.click(screen.getByRole("button", { name: "取消" }));
  await waitFor(() => expect(screen.queryByRole("dialog")).not.toBeInTheDocument());
});
