import { HttpClient, HttpHeaders, HttpParams, HttpResponse } from "@angular/common/http";
import { Token } from "@angular/compiler";
import { Injectable } from "@angular/core";
import { filter, lastValueFrom, Observable } from "rxjs";
import { environment } from "src/app/environments/environment";
import { Domain } from "src/app/model/domain.model";

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

    private domainsUrl = environment.apiURL+'/dr/domain';
    private nameIdentifierControllerPath=environment.apiURL+'/dr/nameIdentifier'
    private priceDetailsUrl=environment.apiURL+'/dr/priceDetails';
    private nameServerUrl=environment.apiURL+'/dr/nameServer'
    private eppDetailsUrl = environment.apiURL+'/dr/registry';
    constructor(private httpClient: HttpClient){}

    getAllDomains(userId: string){
        return this.httpClient.get<any[]>(`${this.domainsUrl}/all?userId=${userId}`,{observe: 'response', headers: new HttpHeaders({
            'Authorization': 'Bearer ' + localStorage.getItem('jwtToken')
        })});
    }

    getAllDomainsByOrgId(orgId: number){
        //console.log(orgId)
        //console.log("jwtToken",localStorage.getItem('jwtToken'))
        return this.httpClient.get<any[]>(`${this.domainsUrl}/get/all?organisationId=${orgId}`,{observe: 'response', headers: new HttpHeaders({
            'Authorization': 'Bearer ' + localStorage.getItem('jwtToken')
        }
        )});
    }

    getLatestPaymentStatuses() {

    return this.httpClient.get<any>(
        `${this.domainsUrl}/latestPaymentStatuses`,
        {
            observe: 'response',
            headers: new HttpHeaders({
                'Authorization': 'Bearer ' + localStorage.getItem('jwtToken')
            })
        }
    );
}

    getFilteredData(filters: any) {
        let params = new HttpParams();
    
        // Add filters to params if they are provided
        if (filters.applicationId) params = params.set('applicationId', filters.applicationId);
        if (filters.userId) params = params.set('userId', filters.userId);
        if (filters.organisationName) params = params.set('organisationName', filters.organisationName);
        if (filters.domainName) params = params.set('domainName',filters.domainName);
        if (filters.nsRecordStatus) params = params.set('nsRecordStatus', filters.nsRecordStatus);
        if (filters.status) params = params.set('status', filters.status);
        if (filters.organisationDetailsId) params = params.set('orgId', filters.organisationDetailsId);
        if (filters.paymentStatus) params = params.set('paymentStatus', filters.paymentStatus);
        if (filters.applicationStatus) params = params.set('applicationStatus', filters.applicationStatus);
        // Log the filters to ensure they are correct
        //console.log('Sending filters:', filters);
        
        // Format the dates before adding them to params
        if (filters.submissionDateFrom) {
            // const formattedFromDate = this.formatDate(filters.submissionDateFrom);
            params = params.set('submissionDateFrom', filters.submissionDateFrom);
        }
        if (filters.submissionDateTo) {
            // const formattedToDate = this.formatDate(filters.submissionDateTo);
            params = params.set('submissionDateTo', filters.submissionDateTo);
        }
        
        // Make the GET request with the query parameters
        return this.httpClient.get<any[]>(`${this.domainsUrl}/all/filter`, { params: params, observe: 'response',headers: new HttpHeaders({
            'Authorization': 'Bearer ' + localStorage.getItem('jwtToken')
        }) });
    }
    
    // Helper method to format dates in ISO 8601 format
    formatDate(date: string): string {
        if (!date) return '';
        const parsedDate = new Date(date);
        return parsedDate.toISOString();  // Convert date to ISO 8601 string
    }
    
    

    getDomainByDomainId(domainId: number){
        return this.httpClient.get<any>(`${this.domainsUrl}/getDetails/${domainId}`, {observe:'response',headers: new HttpHeaders({
            'Authorization': 'Bearer ' + localStorage.getItem('jwtToken')
        })})
    }

    updateDomainDetails(domain: any){
      //console.log(domain)
        return this.httpClient.put<any>(`${this.domainsUrl}/updateDomain/${domain.domainId}`,domain,{observe: 'response',headers: new HttpHeaders({
            'Authorization': 'Bearer ' + localStorage.getItem('jwtToken')
        })});
    }
    updateEntityApprovalDetails(entity: any){
      //console.log(entity)
        return this.httpClient.put<any>(`${this.domainsUrl}/updateDomain/${entity.organisationDetailsId}`,entity,{observe: 'response',headers: new HttpHeaders({
            'Authorization': 'Bearer ' + localStorage.getItem('jwtToken')
        })});
    }

    updatEntityApprovalDetails(domain: any){
      //console.log(domain)
        return this.httpClient.put<any>(`${this.domainsUrl}/updateDomain/${domain.domainId}`,domain,{observe: 'response',headers: new HttpHeaders({
            'Authorization': 'Bearer ' + localStorage.getItem('jwtToken')
        })});
    }

    getAllApplicationInQueue(){
        return this.httpClient.get<any[]>(`${this.domainsUrl}/applicationInQueue`,{observe: 'response',headers: new HttpHeaders({
            'Authorization': 'Bearer ' + localStorage.getItem('jwtToken')
        })});
    }
    uploadPaymentReceipt(formData: FormData): Observable<any> {
        return this.httpClient.post(`${this.domainsUrl}/uploadPaymentReceipt`, formData,{ responseType: 'text',headers: new HttpHeaders({
            'Authorization': 'Bearer ' + localStorage.getItem('jwtToken')
        })});
      }
      updatePaymentReceipt(domainId: number, file: File): Observable<any> {
        const formData = new FormData();
        formData.append('file', file, file.name);
        formData.append('domainId', domainId.toString());
    
        // Perform the PUT request and expect JSON response
        return this.httpClient.put(`${this.domainsUrl}/updatePaymentReceipt/${domainId}`, formData,{headers: new HttpHeaders({
            'Authorization': 'Bearer ' + localStorage.getItem('jwtToken')
        })});
    }
    getAllPriceDetails(){
        return this.httpClient.get<any[]>(`${this.priceDetailsUrl}/getAll`,{observe: 'response',headers: new HttpHeaders({
            'Authorization': 'Bearer ' + localStorage.getItem('jwtToken')
        })});
    }

    createInvoice(domainId : number){
        //console.log("the domain Id is"+ domainId)
        //console.log(localStorage.getItem('jwtToken'))
        return this.httpClient.post<any>(`${this.domainsUrl}/createInvoice/${domainId}`,{},{observe: 'response',headers: new HttpHeaders({
            'Authorization': 'Bearer ' + localStorage.getItem('jwtToken')
        })});
    }

    saveAliasForDomain(domainId, aliasList) {
        return this.httpClient.post<any>(
          `${this.domainsUrl}/createAlias/${domainId}`,
          aliasList, // Send aliasList in the request body
          {
            observe: 'response',
            headers: new HttpHeaders({
              'Authorization': 'Bearer ' + localStorage.getItem('jwtToken')
            })
          }
        );
      }

      getAliasName(aliasName) {
        return this.httpClient.get<any>(
          `${this.domainsUrl}/getAlias/${aliasName}`,
           // Send aliasList in the request body
          {
            observe: 'response',
            headers: new HttpHeaders({
              'Authorization': 'Bearer ' + localStorage.getItem('jwtToken')
            })
          }
        );
      }

      getAllAliasName(domainId) {
        return this.httpClient.get<any>(
          `${this.domainsUrl}/getAllAlias/${domainId}`,
           // Send aliasList in the request body
          {
            observe: 'response',
            headers: new HttpHeaders({
              'Authorization': 'Bearer ' + localStorage.getItem('jwtToken')
            })
          }
        );
      }
   
      updateApplicationAndPaymentStatusBasedOnOrgId(domainId: number, orgId: number,documentStatus: string) {
  return this.httpClient.put<any>(
    `${this.domainsUrl}/updateDomainStatusForOrg/${domainId}/${documentStatus}`,
    { orgId }, // Send orgId in request body
    {
      observe: 'response',
      headers: new HttpHeaders({
        'Authorization': 'Bearer ' + localStorage.getItem('jwtToken'),
        'Content-Type': 'application/json'
      })
    }
  );
}

updateAlias(alias:any){
  return this.httpClient.put<any>(`${this.domainsUrl}/updateAlias`, alias, {
    observe: 'response',
    headers: new HttpHeaders({
      'Authorization': 'Bearer ' + localStorage.getItem('jwtToken'),
      'Content-Type': 'application/json'
    })
  });   
}

 updateTenure(domainId: number, oldTenure: number, newTenure: number): Observable<HttpResponse<any>> {
    const url = `${this.domainsUrl}/updateTenure/${domainId}/${oldTenure}/${newTenure}`;

    // PUT requests typically send a request body.
    // Even if your backend receives the data from the URL path,
    // HttpClient.put expects a body as the second argument.
    // If there's truly no body, you can pass null or an empty object {}.
    // A common practice for updates is to send an object containing the new tenure.
    const requestBody = {
      domainId: domainId, // Include for clarity and if backend prefers body
      oldTenure: oldTenure,
      newTenure: newTenure
    };

    return this.httpClient.put<any>(
      url,
      requestBody, // <-- Corrected: Pass the request body here
      {
        observe: 'response', // This is correct if you want the full HttpResponse
        headers: new HttpHeaders({
          'Authorization': 'Bearer ' + localStorage.getItem('jwtToken'),
          'Content-Type': 'application/json' // Good practice for JSON body
        })
      }
    );
  }

 saveNsHistory(nsHistory: any) {
  const url = `${this.nameServerUrl}/savePurchaseHistoryOfNameServer`;

  return this.httpClient.post<boolean>(url, nsHistory, {
    observe: 'response', // This allows you to get the full HttpResponse
    headers: new HttpHeaders({
      'Authorization': 'Bearer ' + localStorage.getItem('jwtToken'),
      'Content-Type': 'application/json'
    })
  });
}
saveNIHistory(nsHistory: any) {
  const url = `${this.domainsUrl}/savePurchaseHistoryOfNameIdentifier`;

  return this.httpClient.post<boolean>(url, nsHistory, {
    observe: 'response', // This allows you to get the full HttpResponse
    headers: new HttpHeaders({
      'Authorization': 'Bearer ' + localStorage.getItem('jwtToken'),
      'Content-Type': 'application/json'
    })
  });
}

    getorphanData(){
        return this.httpClient.get<any[]>(`${this.domainsUrl}/fetchorphanData`,{observe: 'response', headers: new HttpHeaders({
            'Authorization': 'Bearer ' + localStorage.getItem('jwtToken')
        })});
    }

    deleteOrphanDomainData(domainId : number, orgId : number){
        return this.httpClient.delete(`${this.domainsUrl}/orphanData/${domainId}/${orgId}`,{observe: 'response', headers: new HttpHeaders({
            'Authorization': 'Bearer ' + localStorage.getItem('jwtToken')
        })});

    }

updateDomainBasedOnisCoOperativeBank(domainId: number): Observable<any> {
  const token = localStorage.getItem('tokn') || localStorage.getItem('jwtToken');

  return this.httpClient.put<any>(
    `${this.domainsUrl}/updateDomainBasedOnisCoOperativeBank/${domainId}`,
    {},  // body is empty in this case
    {
      observe: 'response',
      headers: new HttpHeaders({
        'Authorization': 'Bearer ' + token
      })
    }
  );
}

 sendEmailfordeletingOrphanDomainData(domainId : number, organisationId : number){
        return this.httpClient.post<boolean>(`${this.domainsUrl}/sendDeleteEmail/${organisationId}/${domainId}`,{observe: 'response', headers: new HttpHeaders({
            'Authorization': 'Bearer ' + localStorage.getItem('jwtToken')
        })});

    }
 getNameServerCountOfDomain(domainId: any){
  const token = localStorage.getItem('tokn') || localStorage.getItem('jwtToken');
  return this.httpClient.get<number>(`${this.domainsUrl}/getNameServerCount/${domainId}`,
    {observe:'response',
      headers: new HttpHeaders({
        'Authorization':'Bearer '+token
      })
    }
  )
}

//  createInvoiceForNsPurchase(nsPurchase: any): Promise<HttpResponse<any>> {
//     const headers = new HttpHeaders({
//       'Authorization': 'Bearer ' + localStorage.getItem('jwtToken')
//     });
//     const observable = this.httpClient.post<any>(
//       `${this.domainsUrl}/createInvoiceForNsPurchase/${nsPurchase.domainId}`,
//       {},
//       { observe: 'response', headers: headers }
//     );
//     return lastValueFrom(observable);
//   }
   createInvoiceForNsPurchase(nsPurchase: any): Promise<HttpResponse<any>> {
    const headers = new HttpHeaders({
      'Authorization': 'Bearer ' + localStorage.getItem('jwtToken')
    });
    const observable = this.httpClient.post<any>(
      `${this.domainsUrl}/createInvoiceForNsPurchase`, // <-- URL without the domainId
      nsPurchase, // <-- Sending the entire nsPurchase object as the request body
      { observe: 'response', headers: headers }
    );
    return lastValueFrom(observable);
  }

  createInvoiceForNIPurchase(nsPurchase: any): Promise<HttpResponse<any>> {
    const headers = new HttpHeaders({
      'Authorization': 'Bearer ' + localStorage.getItem('jwtToken')
    });
    const observable = this.httpClient.post<any>(
      `${this.domainsUrl}/createInvoiceForNiPurchase`, // <-- URL without the domainId
      nsPurchase, // <-- Sending the entire nsPurchase object as the request body
      { observe: 'response', headers: headers }
    );
    return lastValueFrom(observable);
  }

  updateDomainBasedOnisCoOperativeBankWithInvoice(domainId: number): Observable<any> {
  const token = localStorage.getItem('tokn') || localStorage.getItem('jwtToken');

  return this.httpClient.put<any>(
    `${this.domainsUrl}/updateDomainBasedOnisCoOperativeBankWithInvoice/${domainId}`,
    {},  // body is empty in this case
    {
      observe: 'response',
      headers: new HttpHeaders({
        'Authorization': 'Bearer ' + token
      })
    }
  );
}
 getAllDomainsByOrgIdAsc(orgId: number){
        //console.log(orgId)
        //console.log("jwtToken",localStorage.getItem('jwtToken'))
        return this.httpClient.get<any[]>(`${this.domainsUrl}/getDomainInAscForOrg/${orgId}`,{observe: 'response', headers: new HttpHeaders({
            'Authorization': 'Bearer ' + localStorage.getItem('jwtToken')
        }
        )});
    }

   softDeleteNameIdentifier(nameIdentifierId: number): Observable<HttpResponse<any>> {
    return this.httpClient.delete<any>(
      `${this.nameIdentifierControllerPath}/delete/${nameIdentifierId}`,
      {
        observe: 'response',
        headers: new HttpHeaders({
          'Authorization': 'Bearer ' + localStorage.getItem('jwtToken')
        })
      }
    );
  }

   updateOrgIdForAlias(orgId: any,domainId:any){
      //console.log(domain)
     return this.httpClient.put<any>(`${this.nameIdentifierControllerPath}/updateAll/${orgId}/${domainId}`, null, {
    observe: 'response',
    headers: new HttpHeaders({
        'Authorization': 'Bearer ' + localStorage.getItem('jwtToken')
    })
    });
    }

    getDomainsByUserEmail(emailId){
          return this.httpClient.get<any[]>(`${this.domainsUrl}/getDomainByUserEmail/${emailId}`,{observe: 'response', headers: new HttpHeaders({
            'Authorization': 'Bearer ' + localStorage.getItem('jwtToken')
        }
        )});
    }

      getDomainInNixi(domainName){
          return this.httpClient.get<Boolean>(`${this.eppDetailsUrl}/checkDomain/${domainName}`,{observe: 'response', headers: new HttpHeaders({
            'Authorization': 'Bearer ' + localStorage.getItem('jwtToken')
        }
        )});
    }

    getPaymentReceipt(domainId: number) {
  return this.httpClient.get<any>(
    `${this.domainsUrl}/payment-receipt/${domainId}`,
    {
      observe: 'response',
      headers: new HttpHeaders({
        'Authorization': 'Bearer ' + localStorage.getItem('jwtToken')
      })
    }
  );
}

previewDomainRenewal(domainId: number, renewTenure: number) {
  return this.httpClient.get<any>(
    `${this.domainsUrl}/renewal/preview`,
    {
      params: {
        domainId: domainId.toString(),
        renewTenure: renewTenure.toString()
      },
      headers: new HttpHeaders({
        'Authorization': 'Bearer ' + localStorage.getItem('jwtToken')
      })
    }
  );
}


initiateBatchRenewal(payload: { domainIds: number[]; renewTenure: number }) {
  return this.httpClient.post<any>(
    `${this.domainsUrl}/renewal/initiate-batch`,
    payload,
    {
      headers: new HttpHeaders({
        'Authorization': 'Bearer ' + localStorage.getItem('jwtToken')
      })
    }
  );
}


payBatchRenewal(batchId: string) {
  return this.httpClient.post<any>(
    `${this.domainsUrl}/renewal/pay-batch/${batchId}`,
    {},
    {
      headers: new HttpHeaders({
        'Authorization': 'Bearer ' + localStorage.getItem('jwtToken')
      })
    }
  );
}

initiateDomainRenewal(payload: { domainId: number; renewTenure: number }) {
  return this.httpClient.post<any>(
    `${this.domainsUrl}/renewal/initiate`,
    payload,
    {
      headers: new HttpHeaders({
        'Authorization': 'Bearer ' + localStorage.getItem('jwtToken')
      })
    }
  );
}

payDomainRenewal(renewalId: number) {
  return this.httpClient.post<any>(
    `${this.domainsUrl}/renewal/pay/${renewalId}`,
    {},
    {
      headers: new HttpHeaders({
        'Authorization': 'Bearer ' + localStorage.getItem('jwtToken')
      })
    }
  );
}

getActiveRenewal(domainId: number) {
  return this.httpClient.get<any>(
    `${this.domainsUrl}/renewal/active/${domainId}`,
    {
      headers: new HttpHeaders({
        Authorization: 'Bearer ' + localStorage.getItem('jwtToken'),
      }),
    }
  );
}


getLatestRenewal(domainId: number) {
  return this.httpClient.get(
    `${this.domainsUrl}/renewal/latest-renewal/${domainId}`,
     {
      headers: new HttpHeaders({
        Authorization: 'Bearer ' + localStorage.getItem('jwtToken'),
      }),
    }
  );
}


// ===============================
// 🔁 RENEWAL PAYMENT RECEIPT
// ===============================

uploadRenewalPaymentReceipt(
  domainId: number,
  renewalId: number,
  file: File
) {
  const formData = new FormData();
  formData.append('file', file);
  formData.append('domainId', domainId.toString());
  formData.append('renewalId', renewalId.toString());

  return this.httpClient.post(
    `${this.domainsUrl}/renewal/uploadPaymentReceipt`,
    formData,
    {
      headers: new HttpHeaders({
        Authorization: 'Bearer ' + localStorage.getItem('jwtToken'),
      }),
      responseType: 'text',
    }
  );
}

updateRenewalPaymentReceipt(
  domainId: number,
  renewalId: number,
  file: File
) {
  const formData = new FormData();
  formData.append('file', file);
  formData.append('domainId', domainId.toString());
  formData.append('renewalId', renewalId.toString());

  return this.httpClient.post(
    `${this.domainsUrl}/renewal/updatePaymentReceipt`,
    formData,
    {
      headers: new HttpHeaders({
        Authorization: 'Bearer ' + localStorage.getItem('jwtToken'),
      }),
    }
  );
}

getRenewalPaymentReceipt(domainId: number, renewalId: number) {
  return this.httpClient.get<any>(
    `${this.domainsUrl}/renewal/payment-receipt/${domainId}/${renewalId}`,
    {
      headers: new HttpHeaders({
        Authorization: 'Bearer ' + localStorage.getItem('jwtToken'),
      }),
    }
  );
}

approveRenewal(renewalId: number) {
  return this.httpClient.post(
    `${this.domainsUrl}/renewal/approve/${renewalId}`,
    {},   // body
    {
      headers: new HttpHeaders({
        Authorization: 'Bearer ' + localStorage.getItem('jwtToken')
      })
    }
  );
}


rejectRenewal(renewalId: number) {
  return this.httpClient.post(
    `${this.domainsUrl}/renewal/reject/${renewalId}`,
    {},   // body
    {
      headers: new HttpHeaders({
        Authorization: 'Bearer ' + localStorage.getItem('jwtToken')
      })
    }
  );
}

getRenewalsForRegistrar() {
  return this.httpClient.get<any[]>(
    `${this.domainsUrl}/renewal/pending`,
    {
      headers: new HttpHeaders({
        Authorization: 'Bearer ' + localStorage.getItem('jwtToken')
      })
    }
  );
}

deleteDomainInNixi(domainId: number) {
  return this.httpClient.post(
    `${this.domainsUrl}/renewal/delete-from-nixi/${domainId}`,
    {},
    {
      headers: new HttpHeaders({
        Authorization: 'Bearer ' + localStorage.getItem('jwtToken')
      })
    }
  );
}

requestRestore(domainId: number) {
  return this.httpClient.post(
    `${this.domainsUrl}/renewal/requestRestore/${domainId}`,
    {},
    {
      headers: new HttpHeaders({
        Authorization: 'Bearer ' + localStorage.getItem('jwtToken')
      })
    }
  );
}


approveRestore(domainId: number) {
  return this.httpClient.post(
    `${this.domainsUrl}/renewal/approveRestore/${domainId}`,
    {},
    {
      headers: new HttpHeaders({
        Authorization: 'Bearer ' + localStorage.getItem('jwtToken')
      })
    }
  );
}


//DSC Declartion Methods

getUndertakingHash(
  domainId: number,
  desg: string,
  name: string
) {

  return this.httpClient.get(
    `${this.domainsUrl}/getUndertakingHash`,
    {
      params: {
        domainId: domainId,
        desg: desg,
        name: name
      },
      headers: new HttpHeaders({
        'Authorization':
          'Bearer ' + localStorage.getItem('jwtToken')
      }),
      responseType: 'text'
    }
  );
}


saveSignedUndertaking(payload: any) {

  return this.httpClient.post(
    `${this.domainsUrl}/saveSignedUndertaking`,
    payload,
    {
      headers: new HttpHeaders({
        'Authorization':
          'Bearer ' + localStorage.getItem('jwtToken')
      }),
      responseType: 'text'
    }
  );
}


//END DSC Declartion methods



// uploadBatchReceipt(batchId: string, file: File) {
//   const formData = new FormData();
//   formData.append('batchId', batchId);
//   formData.append('file', file);

//   return this.httpClient.post(
//     `${this.domainsUrl}/renewal/upload-batch-receipt`,
//     formData,
//     {
//       headers: new HttpHeaders({
//         Authorization: 'Bearer ' + localStorage.getItem('jwtToken')
//       }),
//       responseType: 'text'
//     }
//   );
// }


// updateBatchReceipt(batchId: string, file: File) {
//   const formData = new FormData();
//   formData.append('batchId', batchId);
//   formData.append('file', file);

//   return this.httpClient.post(
//     `${this.domainsUrl}/renewal/update-batch-receipt`,
//     formData,
//     {
//       headers: new HttpHeaders({
//         Authorization: 'Bearer ' + localStorage.getItem('jwtToken')
//       }),
//       responseType: 'text'
//     }
//   );
// }

// getBatchReceipt(batchId: string) {
//   return this.httpClient.get<any>(
//     `${this.domainsUrl}/renewal/batch-receipt/${batchId}`,
//     {
//       headers: new HttpHeaders({
//         Authorization: 'Bearer ' + localStorage.getItem('jwtToken')
//       })
//     }
//   );
// }

// downloadBatchReceipt(batchId: string) {
//   return this.httpClient.get(
//     `${this.domainsUrl}/renewal/download-batch-receipt/${batchId}`,
//     {
//       responseType: 'blob',
//       headers: new HttpHeaders({
//         Authorization: 'Bearer ' + localStorage.getItem('jwtToken')
//       })
//     }
//   );
// }

// getActiveBatchRenewal(batchId: string) {
//   return this.httpClient.get<any>(
//     `${this.domainsUrl}/renewal/active-batch/${batchId}`,
//     {
//       headers: new HttpHeaders({
//         Authorization: 'Bearer ' + localStorage.getItem('jwtToken')
//       })
//     }
//   );
// }


}