import { render, screen } from '@testing-library/react';
import user from '@testing-library/user-event';
import { IsNotEmpty } from 'class-validator';
import React from 'react';
import { SubmitHandler, useForm } from 'react-hook-form';
import { classValidatorResolver } from '..';

class Schema {
  @IsNotEmpty()
  username: string;

  @IsNotEmpty()
  password: string;
}

interface Props {
  onSubmit: SubmitHandler<Schema>;
}

function TestComponent({ onSubmit }: Props) {
  const {
    register,
    formState: { errors },
    handleSubmit,
  } = useForm<Schema>({
    resolver: classValidatorResolver(Schema),
  });

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <input {...register('username')} />
      {errors.username && <span role="alert">{errors.username.message}</span>}

      <input {...register('password')} />
      {errors.password && <span role="alert">{errors.password.message}</span>}

      <button type="submit">submit</button>
    </form>
  );
}

test("form's validation with Class Validator and TypeScript's integration", async () => {
  const handleSubmit = vi.fn();
  render(<TestComponent onSubmit={handleSubmit} />);

  expect(screen.queryAllByRole('alert')).toHaveLength(0);

  await user.click(screen.getByText(/submit/i));

  expect(screen.getByText(/username should not be empty/i)).toBeInTheDocument();
  expect(screen.getByText(/password should not be empty/i)).toBeInTheDocument();
  expect(handleSubmit).not.toHaveBeenCalled();
});
