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

interface PosSaleInvoiceState extends EntityState<ISaleInvoiceFullResponse> {}

@Injectable({
  providedIn: 'root',
})
export class PosSaleInvoiceStore extends EntityStore<ISaleInvoiceFullResponse, PosSaleInvoiceState> {
  private readonly service = inject(PosSaleInvoicesService);

  constructor() {
    super({
      ...defaultBaseStateData,
    });
  }

  getData(invoiceId: string) {
    this.patchState({ loading: true });
    this.service
      .getSingle(invoiceId)
      .pipe(
        finalize(() => {
          this.patchState({ loading: false });
        }),
        catchError((error) => {
          this.setError(error);
          throw error;
        }),
      )
      .subscribe((entity) => {
        this.patchState({ entity });
      });
  }

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