import { afterEach, expect, test, vi } from "vitest";
import { setAccessToken, setSelectedAppCode } from "@/shared/api/request";
import {
    deletePointWithdrawalCoinSeller,
    listPointWithdrawalCoinSellers,
    upsertPointWithdrawalCoinSeller,
} from "./pointWithdrawalApi";

afterEach(() => {
    setAccessToken("");
    setSelectedAppCode("lalu");
    vi.unstubAllGlobals();
});

test("point withdrawal whitelist APIs use selected app scope and server-owned ratio payload", async () => {
    setSelectedAppCode("fami");
    vi.stubGlobal(
        "fetch",
        vi.fn(async () => new Response(JSON.stringify({ code: 0, data: { items: [] } }))),
    );

    await listPointWithdrawalCoinSellers();
    await upsertPointWithdrawalCoinSeller({
        sellerUserId: 90001,
        sortOrder: 1,
        pointAmount: 100000,
        sellerCoinAmount: 92000,
        serviceCountryCodes: ["SA"],
        status: "active",
    });
    await deletePointWithdrawalCoinSeller("90001");

    const [listUrl, listInit] = vi.mocked(fetch).mock.calls[0];
    const [putUrl, putInit] = vi.mocked(fetch).mock.calls[1];
    const [deleteUrl, deleteInit] = vi.mocked(fetch).mock.calls[2];
    expect(String(listUrl)).toContain("/api/v1/admin/point-withdrawal/coin-sellers");
    expect(listInit?.headers).toMatchObject({ "X-App-Code": "fami" });
    expect(String(putUrl)).toContain("/api/v1/admin/point-withdrawal/coin-sellers");
    expect(putInit?.method).toBe("PUT");
    expect(JSON.parse(String(putInit?.body))).toMatchObject({
        pointAmount: 100000,
        sellerCoinAmount: 92000,
        serviceCountryCodes: ["SA"],
    });
    expect(String(deleteUrl)).toContain("/api/v1/admin/point-withdrawal/coin-sellers/90001");
    expect(deleteInit?.method).toBe("DELETE");
});
