import { defaultBaseStateData, EntityState, EntityStore } from '@/core/state';
import { HttpErrorResponse } from '@angular/common/http';
import { inject, Injectable } from '@angular/core';
import { catchError, finalize, map } from 'rxjs';
import { IPosProfileResponse } from '../models';
import { PosService } from '../modules/landing/services/main.service';

interface PosProfileState extends EntityState<IPosProfileResponse> {}

@Injectable({
  providedIn: 'root',
})
export class PosProfileStore extends EntityStore<IPosProfileResponse, PosProfileState> {
  private readonly service = inject(PosService);

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

  getData() {
    this.patchState({ loading: true });
    return this.service.getProfile().pipe(
      finalize(() => {
        this.patchState({ loading: false });
      }),

      catchError((err: HttpErrorResponse) => {
        this.setError(err);
        // if (err.status === 403) debugger;
        throw err;
      }),

      map((entity: IPosProfileResponse) => {
        if (entity) {
          this.setEntity(entity);
        }
        return entity;
      }),
    );
  }

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