import { HttpClient, HttpHeaders, HttpParams, HttpResponse } from "@angular/common/http";
import { Injectable } from "@angular/core";
import { param } from "jquery";
import { lastValueFrom, Observable } from "rxjs";
import { environment } from "src/app/environments/environment";
import { Roles } from "src/app/model/roles.model";

@Injectable({
    providedIn : 'root'
})
export class UserService{

    private drRegUrl = environment.apiURL+'/dr/user/save';
    private getAllUsersUrl = environment.apiURL+'/dr/user/all';
    private getUserUrl = environment.apiURL+'/dr/user/getDetails';
    private updateUserUrl = environment.apiURL+'/dr/user/update';
    private updateUserRoleUrl = environment.apiURL+'/dr/user/roles';
    private deleteUserUrl = environment.apiURL+'/dr/user/delete';
    private getUserByEmailUrl = environment.apiURL+'/dr/user/get';
    private deleteadminUrl = environment.apiURL+'/dr/administrativeContact/delete';
    private deletebillnUrl = environment.apiURL+'/dr/billingContact/delete';
    private deletetechUrl = environment.apiURL+'/dr/technicalContact/delete';
    private rgtrRegUrl = environment.apiURL+'/dr/rgtrUser'
     private rgntUserUrl = environment.apiURL+'/dr/user'
    constructor(private httpClient: HttpClient){

    }

    getAllUsers(organisationId: number){
        const url = `${this.getAllUsersUrl}?organisationId=${organisationId}`;
        //console.log('API URL:', url); 
        return this.httpClient.get<any[]>(url, { observe: 'response' });
    }

    saveUser(user: any){
        return this.httpClient.post<void>(this.drRegUrl,user,{observe: 'response'});
    }
    saveRgtrUser(user: any){
        return this.httpClient.post<void>(this.rgtrRegUrl+"/"+"save",user,{observe: 'response'});
    }
    getUserById(id: number){
        return this.httpClient.get<any>(this.getUserUrl+"/"+id,{observe:'response'})
    }

    updateUser(user: any){
        
        return this.httpClient.put<any>(this.updateUserUrl, user, {observe: 'response'});
    }

   updateUserRole(
    userRoles: Roles[],
    email: string,
    isDeleted?: boolean // This is the new optional parameter
  ): Observable<HttpResponse<any>> {
    let params = new HttpParams().set('email', email);

    // Conditionally add the optional parameter if it's provided
    if (isDeleted !== undefined) {
      params = params.set('isDeleted', isDeleted.toString());
    }

    return this.httpClient.put(this.updateUserRoleUrl, userRoles, {
      observe: 'response',
      params: params,
      responseType: 'text'
    });
  }


    deleteUserById(id: number){
        return this.httpClient.delete<void>(this.deleteUserUrl+"/"+id, {observe: 'response'});
    }

     verifyEmailId(userId: string){
        return this.httpClient.get<void>(this.deleteUserUrl+"/verify-user/"+userId, {observe: 'response'});
    }

    deleteUserByUserId(email: string, deletedBy?: string, userRole?: string) {
      let params = new HttpParams();
      if (deletedBy) { 
         params = params.set('deletedBy', deletedBy),
          params.set('userRole', userRole);
      }
     
      return this.httpClient.delete<void>(this.deleteUserUrl + "/" + email, { observe: 'response', params });
    }
    deleteBillById(id: number, contactRole: string) {
        return this.httpClient.delete<void>(`${this.deletebillnUrl}/${id}?contactRole=${contactRole}`, { observe: 'response' });
      }
      deleteTechById(id: number, contactRole: string) {
        return this.httpClient.delete<void>(`${this.deletetechUrl}/${id}?contactRole=${contactRole}`, { observe: 'response' });
      }
      deleteAdminById(id: number, contactRole: string) {
        return this.httpClient.delete<void>(`${this.deleteadminUrl}/${id}?contactRole=${contactRole}`, { observe: 'response' });
      }
      
    getUserByEmailId(userId: string){
        return this.httpClient.get<any>(this.getUserByEmailUrl+"/"+userId, {observe: 'response'});
    }
    getRgtrUserByEmailId(userId: string){
        return this.httpClient.get<any>(this.rgtrRegUrl+"/"+"getUser"+"/"+userId, {observe: 'response'});
    }
    // getAllRgtrUsers(){
    //     return this.httpClient.get<any>(this.rgtrRegUrl+"/"+"all", {observe: 'response'});
    // }
    getAllRgtrUsers(){
        return this.httpClient.get<any>(this.rgtrRegUrl+"/"+"all", {observe: 'response', headers: new HttpHeaders({
            'Authorization': 'Bearer ' + localStorage.getItem('jwtToken')
        }
        )});
    }
    getAllActiveUsers(){
        const url = environment.apiURL+"/dr/user";
        //console.log('API URL:', url); 
        return this.httpClient.get<number>(url+"/"+"activeUser", { observe: 'response' });
    }

//    getAllDynamicText() {
//   return this.httpClient.get<any>(
//     'http://localhost:8443/dr/rgtrUser/getAlltext',
//     { observe: 'response' }
//   );
// }
    getAllDynamicText(){
        return this.httpClient.get<any>(this.rgtrRegUrl+"/"+"getAlltext", {observe: 'response'})
    }

    getAllActiveLink(){
        const url = environment.apiURL+"/dr/links";
        //console.log('API URL:', url); 
        return this.httpClient.get<number>(url+"/"+"all", { observe: 'response' });
    }
      markAsDeletedByEmailId(email: string,userRole: string): Observable<string> { // <--- Changed <any> to <string>
    // Construct HttpParams to send the email as a query parameter
   let params = new HttpParams()
    .set('email', email)
    .set('userRole', userRole); 

    // Make the PUT request with the query parameter
    return this.httpClient.put(
      `${this.rgntUserUrl}/markUserAsDelete`,
      null,
      {
        params: params,
        responseType: 'text' // This tells Angular to expect a plain text response
      }
    );
  }

   getAllDeletedUsers(){
        const url = environment.apiURL+"/dr/user";
        return this.httpClient.get<[]>(this.rgntUserUrl+"/"+"deleted-users", { observe: 'response' });
    }

    getRestoredUser(rgntUserAuditId: number){
        return this.httpClient.get<any>(this.rgntUserUrl+"/restore/"+rgntUserAuditId, {observe: 'response'});
    }

    getAllOrphanUsers(){
        return this.httpClient.get<[]>(this.rgntUserUrl+"/"+"orphan-users", { observe: 'response' });
    }

    deleteOrphanUser(userEmailId: string){
        return this.httpClient.delete<any>(this.rgntUserUrl+"/deleteOrphanUser/"+userEmailId, {observe: 'response'});
    }

}