import { defaultBaseStateData, EntityState, EntityStore } from '@/core/state';
import { HttpErrorResponse } from '@angular/common/http';
import { computed, inject, Injectable } from '@angular/core';
import { CookieService } from 'ngx-cookie-service';
import { catchError, finalize, map } from 'rxjs';
import { COOKIE_KEYS } from 'src/assets/constants';
import { IPosInfoResponse } from '../models/pos.io';
import { PosService } from '../modules/landing/services/main.service';

interface PosState extends EntityState<IPosInfoResponse> {
  posId: string;
}

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

  constructor(private readonly cookieService: CookieService) {
    super({
      ...defaultBaseStateData,
      posId: cookieService.get(COOKIE_KEYS.POS_ID),
    });
  }

  posId = computed(() => this._state().posId);

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

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

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

  override reset(): void {
    this.setState({
      ...defaultBaseStateData,
      posId: this.cookieService.get(COOKIE_KEYS.POS_ID),
    });
  }
}
