import { defaultBaseStateData, EntityState, EntityStore } from '@/core/state';
import { inject, Injectable } from '@angular/core';
import { catchError, finalize } from 'rxjs';
import { IPosStatisticsResponse } from '../models';
import { PosStatisticsService } from '../services/main.service';

interface PosStatisticsState extends EntityState<IPosStatisticsResponse> {
  lastFromDate: Date;
}

@Injectable({
  providedIn: 'root',
})
export class PosStatisticsStore extends EntityStore<IPosStatisticsResponse, PosStatisticsState> {
  private readonly service = inject(PosStatisticsService);
  constructor() {
    super({
      ...defaultBaseStateData,
      lastFromDate: new Date(),
    });
  }

  getData(fromDate?: Date) {
    if (fromDate && fromDate.getTime() === this._state().lastFromDate.getTime()) {
      return;
    }
    this.patchState({ loading: true, lastFromDate: fromDate || new Date() });
    this.service
      .getAll(fromDate)
      .pipe(
        finalize(() => {
          this.patchState({ loading: false });
        }),
        catchError((error) => {
          this.setError(error);
          throw error;
        })
      )
      .subscribe((entity) => {
        this.patchState({ entity });
      });
  }

  override reset(): void {
    this.setState({
      ...defaultBaseStateData,
      lastFromDate: new Date(),
    });
  }
}
