import { Injectable } from '@angular/core';
import {
  HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HttpResponse
} from '@angular/common/http';
import { Observable, of } from 'rxjs';
import { tap } from 'rxjs/operators';
import { CachingService } from './caching.service';
import { CACHEABLE_URLS } from '../config/caching.config';

@Injectable()
export class CachingInterceptor implements HttpInterceptor {

  constructor(private cache: CachingService) {}

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    console.log('Caching interceptor:', req.urlWithParams, 'isCacheable:', this.isCacheable(req));
    if (!this.isCacheable(req)) {
      return next.handle(req);
    }

    const cachedResponse = this.cache.get(this.getCacheKey(req));
    if (cachedResponse) {
      return of(cachedResponse.clone());
    }

    return next.handle(req).pipe(
      tap(event => {
        if (event instanceof HttpResponse) {
          this.cache.put(this.getCacheKey(req), event.clone());
        }
      })
    );
  }

  private isCacheable(req: HttpRequest<any>): boolean {
    const checkUrl = (methodUrls: string[]) => {
      return methodUrls.some(url => {
        // Regex to match the configured URL, and ensure it's not just a partial match of a larger URL segment.
        // e.g. /api/user should match /api/user, /api/user/123, /api/user?query=1
        // but not /api/user-roles
        const regex = new RegExp(url + '($|/|\\?)');
        return regex.test(req.urlWithParams);
      });
    };

    if (req.method === 'GET') {
      return checkUrl(CACHEABLE_URLS.GET);
    }

    if (req.method === 'POST') {
      return checkUrl(CACHEABLE_URLS.POST);
    }

    return false;
  }

  private getCacheKey(req: HttpRequest<any>): string {
    if (req.method === 'POST') {
      return req.urlWithParams + JSON.stringify(req.body);
    }
    return req.urlWithParams;
  }
}
