import { describe, it, expect, beforeEach, vi } from "vitest";
import { screen, fireEvent } from "@testing-library/react";
import { renderWithProviders } from "../test/utils";

vi.mock("sonner", () => ({ toast: { success: vi.fn(), error: vi.fn(), warning: vi.fn() } }));
vi.mock("../lib/api", () => ({
    api: { get: vi.fn(), post: vi.fn(), patch: vi.fn(), put: vi.fn(), delete: vi.fn() },
    ApiError: class extends Error {},
}));
vi.mock("../stores/authStore", () => ({
    useAuthStore: () => ({ doctorUuid: null, dbUuid: "clinic-1", primaryRole: "clinic" }),
}));
vi.mock("../hooks/useSubscription", () => ({
    useSubscription: () => ({ maxSecretaries: 5 }),
}));

import { api } from "../lib/api";
import MySecretariesPage from "./MySecretariesPage";

const get = api.get as ReturnType<typeof vi.fn>;

beforeEach(() => {
    get.mockReset();
    get.mockImplementation((url: string) => {
        if (url.includes("/clinic/doctor-list/"))
            return Promise.resolve({ success: true, data: { data: [
                { uuid: "doc-a", name: "دکتر الف" },
                { uuid: "doc-b", name: "دکتر ب" },
            ] } });
        if (url.includes("/secretaries/clinic/")) return Promise.resolve({ success: true, data: [] });
        return Promise.resolve({ success: true, data: [] });
    });
});

describe("MySecretariesPage — clinic multi-doctor", () => {
    it("shows the doctor multi-select inside the add modal", async () => {
        renderWithProviders(<MySecretariesPage />, { route: "/admin/my-secretaries" });
        // پیکر روی صفحه نیست تا وقتی مودال باز شود
        expect(screen.queryByText("پزشکانِ این منشی")).not.toBeInTheDocument();

        fireEvent.click(await screen.findByText("اضافه کردن منشی"));

        expect(await screen.findByText("پزشکانِ این منشی")).toBeInTheDocument();
        expect(screen.getByText("دکتر الف")).toBeInTheDocument();
        expect(screen.getByText("دکتر ب")).toBeInTheDocument();
        expect(screen.getByText("انتخاب همه")).toBeInTheDocument();
    });

    it("selecting all picks every clinic doctor", async () => {
        renderWithProviders(<MySecretariesPage />, { route: "/admin/my-secretaries" });
        fireEvent.click(await screen.findByText("اضافه کردن منشی"));
        await screen.findByText("پزشکانِ این منشی");

        fireEvent.click(screen.getByText("انتخاب همه"));
        expect(screen.getByText(/[۲2] انتخاب‌شده/)).toBeInTheDocument();
        expect(screen.getByText("لغو همه")).toBeInTheDocument();
    });
});
