import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable, timer } from 'rxjs';
import { retry } from 'rxjs/operators';
import { ApiConfigService } from '../../config/api-config.service';
import { CategoryDto } from '../dto/category.dto';
import { CategoryRepository } from './category.repository';

@Injectable({ providedIn: 'root' })
export class ApiCategoryRepository implements CategoryRepository {
  private readonly retryConfig = {
    count: 2,
    delay: (_error: unknown, retryCount: number) => timer(Math.pow(2, retryCount) * 500)
  };

  constructor(
    private readonly http: HttpClient,
    private readonly apiConfig: ApiConfigService
  ) {}

  getCategories(): Observable<CategoryDto[]> {
    return this.http.get<CategoryDto[]>(`${this.apiConfig.getBaseUrl()}/category`)
      .pipe(retry(this.retryConfig));
  }
}