import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
import { MemoryRouter } from "react-router-dom";
import { AxiosError, type AxiosResponse } from "axios";
import { afterEach, describe, expect, it, vi } from "vitest";
import { RegisterForm } from "./RegisterForm";

const registerMock = vi.fn();

vi.mock("../api/authApi", () => ({
  register: (...args: unknown[]) => registerMock(...args)
}));

afterEach(() => {
  cleanup();
  registerMock.mockReset();
});

describe("RegisterForm", () => {
  it("renders register form controls", () => {
    render(
      <MemoryRouter>
        <RegisterForm />
      </MemoryRouter>
    );
    expect(screen.getByPlaceholderText("Email")).toBeInTheDocument();
    expect(screen.getByPlaceholderText("Password")).toBeInTheDocument();
    expect(screen.getByText(/uppercase, lowercase, and a digit/i)).toBeInTheDocument();
    expect(screen.getByText(/privacy policy/i)).toBeInTheDocument();
  });

  it("shows validation error from API", async () => {
    registerMock.mockRejectedValueOnce(
      new AxiosError(
        "Validation failed",
        "422",
        undefined,
        undefined,
        {
          status: 422,
          data: {
            detail: [
              {
                loc: ["body", "password"],
                msg: "Value error, Password must include at least one uppercase letter"
              }
            ]
          }
        } as AxiosResponse
      )
    );

    render(
      <MemoryRouter>
        <RegisterForm />
      </MemoryRouter>
    );
    fireEvent.change(screen.getByPlaceholderText("Email"), {
      target: { value: "user@example.com" }
    });
    fireEvent.change(screen.getByPlaceholderText("Password"), {
      target: { value: "valid123" }
    });
    fireEvent.click(screen.getByRole("checkbox"));
    fireEvent.click(screen.getByRole("button", { name: "Register" }));

    await waitFor(() => {
      expect(screen.getByRole("alert")).toHaveTextContent(
        "Password must include at least one uppercase letter"
      );
    });
  });
});
