import { Injectable } from '@angular/core';
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { catchError } from 'rxjs/operators';
import { environment } from '../../../environments/environment';

interface PasswordGenerationRequest {
  length: number;
  includeUppercase: boolean;
  includeLowercase: boolean;
  includeNumbers: boolean;
  includeSymbols: boolean;
  excludeCharacters: string;
}

interface PasswordGenerationResponse {
  generatedPassword: string;
  message: string;
  success: boolean;
}

@Injectable({
  providedIn: 'root'
})
export class PasswordGeneratorService {

  private apiUrl = `${environment.apiBaseUrl}/api/v1/password-generator/generate`;

  constructor(private http: HttpClient) { }

  generatePassword(request: PasswordGenerationRequest): Observable<PasswordGenerationResponse> {
    return this.http.post<PasswordGenerationResponse>(this.apiUrl, request)
      .pipe(
        catchError(this.handleError)
      );
  }

  private handleError(error: HttpErrorResponse) {
    let errorMessage = 'An unknown error occurred!';
    if (error.error instanceof ErrorEvent) {
      // Client-side errors
      errorMessage = `Error: ${error.error.message}`;
    } else {
      // Backend errors
      if (error.status === 400 && error.error && error.error.message) {
        errorMessage = error.error.message;
      } else if (error.status) {
        errorMessage = `Server returned code: ${error.status}, error message: ${error.message}`;
      } else {
        errorMessage = `Error Code: ${error.status}\nMessage: ${error.message}`;
      }
    }
    console.error(errorMessage);
    return throwError(() => new Error(errorMessage));
  }
}
