import { describe, it, expect, vi, beforeEach } from "vitest";
import { render, screen } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { MemoryRouter } from "react-router-dom";

vi.mock("@/api/driver", () => ({
  authRequest: vi.fn(async () => ({ status: "code_sent", channel: "tg" })),
  authVerify: vi.fn(async () => ({ token: "T", driver_id: 7 })),
}));

import { LoginPage } from "./LoginPage";
import * as driver from "@/api/driver";
import { useAuth } from "@/store/auth";

const wrap = () => render(<MemoryRouter><LoginPage /></MemoryRouter>);

describe("LoginPage", () => {
  beforeEach(() => useAuth.getState().clear());
  it("requests code then verifies and stores session", async () => {
    wrap();
    expect(screen.getByText(/Вход в приложение/i)).toBeInTheDocument();
    await userEvent.type(screen.getByPlaceholderText(/телефон/i), "9143054400");
    await userEvent.click(screen.getByRole("button", { name: /Получить код/i }));
    expect(driver.authRequest).toHaveBeenCalledWith("79143054400");
    const codeInput = await screen.findByPlaceholderText(/код/i);
    await userEvent.type(codeInput, "123456");
    await userEvent.click(screen.getByRole("button", { name: /Войти/i }));
    expect(driver.authVerify).toHaveBeenCalledWith("79143054400", "123456");
  });
});
