import { Injectable } from '@angular/core';
import {
  HttpInterceptor,
  HttpEvent,
  HttpHandler,
  HttpRequest,
} from '@angular/common/http';
import {
  Observable, map,
} from 'rxjs';
import { Buffer } from 'buffer';
import { AdminDataService } from '../services/admin/admin-data.service';
import { CustomerDataService } from '../services/admin/customer-data.service';

export enum ErrorCode {
  serverDown = 0,
  unauthorised = 401,
  apifailed = 520,
  client = 404,
}

@Injectable()

export class HttpRequestService implements HttpInterceptor {
  private token: string = 'e';
  private tokenExpiration!: number;
  constructor(
    private customerDataService: CustomerDataService,
    private adminDataService: AdminDataService,) { }
  intercept(
    req: HttpRequest<any>,
    next: HttpHandler
  ): Observable<HttpEvent<any>> {
    const csrf: any = document.querySelector('#csrf-token')?.getAttribute('content') ?? '';
    this.token = csrf;
   // for verfication of CSRF token, either we should need to send _token in body or X-CSRF-TOKEN 
    // Check if CSRF token has expired
    
    let requestToken = req.clone({});
    if(req.method == 'POST'){
        requestToken = req.clone({
        headers: req.headers.set('X-CSRF-TOKEN', this.token || csrf)
      });
    }

    // Send the modified request and decrypt the response
    return next.handle(requestToken).pipe(
      map((event: HttpEvent<any>) => {
        if (event.type === 4) { // check if response is complete
          // Check if the CSRF token has been updated in the response headers
          if(req.method == 'GET'){
            const newToken = event.headers.get('X-CSRF-TOKEN');
            if (newToken && newToken !== this.token) {
              // CSRF token has been updated, store the new value
              this.token = newToken;
              this.tokenExpiration = Date.now() + (60 * 60 * 1000); // set the expiration time to 1 hour from now
            }
          }
          
          if (event.body) { // check if the event is an HttpResponse      
            if (event.body?.encrypted) {
              const decryptedData = Buffer.from(event.body.encrypted, 'base64').toString('utf-8'); // decrypt the data using CryptoJS library
              let body = { body: JSON.parse(decryptedData) };
              if(body?.body?.['admin_users_inactive_auto_logout_time']){
                this.adminDataService.setSharedData(body?.body);
              }
              if(body?.body?.['customer_inactive_auto_logout_time']){
                this.customerDataService.setSharedData(body?.body);
              }
              
              return event.clone(body); // parse the decrypted data as JSON and set it as the response body
            }
            return event;
          }
          return event;
        }
        return event;
      })
    );


  }
  
}
