import { TestBed } from '@angular/core/testing';
import { provideRouter, Router } from '@angular/router';
import { of, throwError } from 'rxjs';

import { AuthService } from '../../../../core/services/auth/auth.service';
import { LoginPageComponent } from './login-page.component';

describe('LoginPageComponent', () => {
  beforeEach(() => {
    TestBed.resetTestingModule();
  });

  it('submits credentials and redirects to home with a full page reload on success', async () => {
    const authService = {
      login: vi.fn().mockReturnValue(
        of({
          id: 1,
          nombre_apellido: 'Ada Lovelace',
          email: 'ada@example.com'
        })
      )
    };

    await TestBed.configureTestingModule({
      imports: [LoginPageComponent],
      providers: [provideRouter([]), { provide: AuthService, useValue: authService }]
    }).compileComponents();

    const fixture = TestBed.createComponent(LoginPageComponent);
    const component = fixture.componentInstance as any;
    const router = TestBed.inject(Router);
    const navigateSpy = vi.spyOn(router, 'navigate').mockResolvedValue(true);
    const redirectSpy = vi.spyOn(component, 'redirectToHome').mockImplementation(() => undefined);

    component.form.setValue({
      email: 'ada@example.com',
      password: 'secret123'
    });

    component.onSubmit();

    expect(authService.login).toHaveBeenCalledWith({
      email: 'ada@example.com',
      password: 'secret123'
    });
    expect(redirectSpy).toHaveBeenCalled();
    expect(navigateSpy).not.toHaveBeenCalled();
  });

  it('surfaces backend login errors', async () => {
    const authService = {
      login: vi.fn().mockReturnValue(
        throwError(() => ({
          error: {
            errors: {
              email: ['Las credenciales son invalidas.']
            }
          }
        }))
      )
    };

    await TestBed.configureTestingModule({
      imports: [LoginPageComponent],
      providers: [provideRouter([]), { provide: AuthService, useValue: authService }]
    }).compileComponents();

    const fixture = TestBed.createComponent(LoginPageComponent);
    const component = fixture.componentInstance as any;

    component.form.setValue({
      email: 'ada@example.com',
      password: 'wrong-password'
    });

    component.onSubmit();

    expect(component.serverError()).toBe('Las credenciales son invalidas.');
  });

  it('validates email length and password minimum length before submit', async () => {
    const authService = {
      login: vi.fn()
    };

    await TestBed.configureTestingModule({
      imports: [LoginPageComponent],
      providers: [provideRouter([]), { provide: AuthService, useValue: authService }]
    }).compileComponents();

    const fixture = TestBed.createComponent(LoginPageComponent);
    const component = fixture.componentInstance as any;

    component.form.setValue({
      email: `${'a'.repeat(250)}@example.com`,
      password: '1234567'
    });
    component.onSubmit();

    expect(authService.login).not.toHaveBeenCalled();
    expect(component.getControlError('email')).toBe('No puede superar los 255 caracteres.');
    expect(component.getControlError('password')).toBe('Debe tener al menos 8 caracteres.');
  });
});
