import { CommonModule } from '@angular/common';
import { Component } from '@angular/core';
import { FormControl, FormGroup, ReactiveFormsModule, Validators } from '@angular/forms';
import { MatButtonModule } from '@angular/material/button';
import { MatCardModule } from '@angular/material/card';
import { MatFormFieldModule } from '@angular/material/form-field';
import { MatInputModule } from '@angular/material/input';
import { RouterModule } from '@angular/router';
import { AuthService } from '../../auth.service';

@Component({
  selector: 'app-forgot-password',
  templateUrl: './forgot-password.component.html',
  styleUrls: ['./forgot-password.component.scss'],
  standalone: true,
  imports: [
    CommonModule,
    ReactiveFormsModule,
    MatCardModule,
    MatFormFieldModule,
    MatInputModule,
    MatButtonModule,
    RouterModule
  ]
})
export class ForgotPasswordComponent {

  submitted = false;
  error = false;

  form = new FormGroup({
    email: new FormControl('', [Validators.required, Validators.email])
  });

  constructor(private authService: AuthService) {}

  submit() {
    if (this.form.invalid) { return; }
    const email = this.form.controls.email.value + '';
    this.error = false;

    this.authService.forgotPassword(email).subscribe({
      next: () => { this.submitted = true; },
      error: (err) => {
        // Aus Datenschutzgründen wird bei unbekannter E-Mail dieselbe
        // Erfolgsmeldung angezeigt wie bei einer bekannten Adresse.
        if (err?.error?.errors?.email === 'emailNotExists') {
          this.submitted = true;
          return;
        }
        this.error = true;
      }
    });
  }

}
