import { HttpInterceptorFn, HttpResponse } from '@angular/common/http';
import { of } from 'rxjs';
import { tap } from 'rxjs/operators';

import { CACHE_DURATION_MS, CATEGORY_CACHE_DURATION_MS } from '../config/constants';

const cache = new Map<string, { response: HttpResponse<unknown>, timestamp: number }>();

export const cacheInterceptor: HttpInterceptorFn = (req, next) => {
  // Кэшируем только GET запросы
  if (req.method !== 'GET') {
    return next(req);
  }

  // Кэшируем списки категорий, товары категорий и отдельные товары
  const isCategoryList = /\/category$/.test(req.url);
  const isCategoryItems = /\/category\/[^/?]+/.test(req.url);
  const isItem = /\/items\/[^/?]+/.test(req.url);
  if (!isCategoryList && !isCategoryItems && !isItem) {
    return next(req);
  }

  const ttl = isCategoryList ? CACHE_DURATION_MS : CATEGORY_CACHE_DURATION_MS;

  // Cleanup expired entries before checking
  cleanupExpiredCache();

  const cachedResponse = cache.get(req.url);
  
  // Проверяем наличие и актуальность кэша
  if (cachedResponse) {
    const age = Date.now() - cachedResponse.timestamp;
    if (age < ttl) {
      return of(cachedResponse.response.clone());
    } else {
      cache.delete(req.url);
    }
  }

  // Выполняем запрос и кэшируем ответ
  return next(req).pipe(
    tap(event => {
      if (event instanceof HttpResponse) {
        cache.set(req.url, {
          response: event.clone(),
          timestamp: Date.now()
        });
      }
    })
  );
};

function cleanupExpiredCache(): void {
  const now = Date.now();
  for (const [url, data] of cache.entries()) {
    if (now - data.timestamp >= CACHE_DURATION_MS) {
      cache.delete(url);
    }
  }
}
