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

interface PartnerState extends EntityState<IPartnerResponse> {}

@Injectable({
  providedIn: 'root',
})
export class PartnerStore extends EntityStore<IPartnerResponse, PartnerState> {
  private readonly service = inject(PartnersService);
  constructor() {
    super({
      loading: false,
      error: null,
      entity: null,
      initialized: false,
      isRefreshing: false,
    });
  }

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