import { EntityState, EntityStore } from '@/core/state';
import { computed, inject, Injectable } from '@angular/core';
import { MenuItem } from 'primeng/api';
import { catchError, finalize } from 'rxjs';
import { consumerAccountsNamedRoutes } from '../constants';
import { IAccountResponse } from '../models';
import { AccountsService } from '../services/main.service';

interface AccountState extends EntityState<IAccountResponse> {
  breadcrumbItems: MenuItem[];
}

@Injectable({
  providedIn: 'root',
})
export class AccountStore extends EntityStore<IAccountResponse, AccountState> {
  private readonly service = inject(AccountsService);
  constructor() {
    super({
      loading: false,
      error: null,
      entity: null,
      initialized: false,
      isRefreshing: false,
      breadcrumbItems: [],
    });
  }

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

  private setBreadcrumb(accountId: string) {
    this.patchState({
      breadcrumbItems: [
        {
          ...consumerAccountsNamedRoutes.accounts.meta,
          routerLink: consumerAccountsNamedRoutes.accounts.meta.pagePath!(),
        },
        {
          title: this.entity()?.account.username,
          routerLink: consumerAccountsNamedRoutes.account.meta.pagePath!(accountId),
        },
      ],
    });
  }

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

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