import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { HttpErrorResponse } from '@angular/common/http';
import { ToastrService } from 'ngx-toastr';
import { AuthService } from '../../services/auth.service';
import { RegisterRequest } from '../../models/auth/auth.model';

@Component({
  selector: 'app-register-page',
  templateUrl: './register-page.component.html',
  styleUrls: ['./register-page.component.scss']
})
export class RegisterPageComponent implements OnInit {
  model: RegisterRequest = { email: '', password: '', username: '' };
  isError = false;
  errMsg: string = '';

  constructor(
    private router: Router,
    private authService: AuthService,
    private toastr: ToastrService
  ) { }

  ngOnInit(): void {
  }

  onRegister(): void {
    this.isError = false;
    this.errMsg = '';

    this.authService.register(this.model).subscribe(
      resp => {
        this.toastr.success('Registration successful! Please log in.', 'Success');
        this.router.navigate(['/login']); // Redirect to login page after successful registration
      },
      (errResponse: HttpErrorResponse) => {
        this.isError = true;
        switch (errResponse.status) {
          case 400:
            this.errMsg = 'Registration failed: Invalid input or user already exists.';
            break;
          case 500:
            this.errMsg = 'Internal Server Error';
            break;
          default:
            this.errMsg = 'Registration failed: Server Error';
            break;
        }
        this.toastr.error(this.errMsg, 'Registration Failed');
      }
    );
  }
}
