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

interface UserState extends EntityState<IUserResponse> {}

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

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

  override reset(): void {
    this.setState({
      loading: false,
      error: null,
      entity: null,
      initialized: false,
      isRefreshing: false,
    });
  }
}
