import { describe, expect, it } from "vitest";
import { ApiError, buildUrl, queryString } from "./api";

describe("buildUrl", () => {
    it("joins pretty permalinks", () => {
        expect(buildUrl("https://x.test/wp-json/fxtr/v1/", "bookings?page=2")).toBe(
            "https://x.test/wp-json/fxtr/v1/bookings?page=2",
        );
    });

    it("joins plain permalinks with & instead of a second ?", () => {
        expect(buildUrl("https://x.test/?rest_route=/fxtr/v1/", "/bookings?page=2&status=pending")).toBe(
            "https://x.test/?rest_route=/fxtr/v1/bookings&page=2&status=pending",
        );
    });
});

describe("queryString", () => {
    it("drops empty values", () => {
        expect(queryString({ status: "", page: 1, date: undefined, search: "a b" })).toBe("?page=1&search=a+b");
        expect(queryString({ status: "" })).toBe("");
    });
});

describe("ApiError", () => {
    it("has no field errors unless the server names some", () => {
        expect(new ApiError("Bad", 400).fields).toEqual({});
        expect(new ApiError("Bad", 400, "fxtr_contact_invalid", { email: "Enter a valid email" }).fields.email).toBe(
            "Enter a valid email",
        );
    });
});
