import { defaultBaseStateData, EntityState, EntityStore } from '@/core/state';
import { computed, inject, Injectable } from '@angular/core';
import { MenuItem } from 'primeng/api';
import { catchError, finalize } from 'rxjs';
import { partnerAccountsNamedRoutes } 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({
      ...defaultBaseStateData,
      breadcrumbItems: [],
    });
  }

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

  private setBreadcrumb(accountId: string) {
    this.patchState({
      breadcrumbItems: [
        {
          ...partnerAccountsNamedRoutes.accounts.meta,
          routerLink: partnerAccountsNamedRoutes.accounts.meta.pagePath!(),
        },
        {
          title: this.entity()?.account.username,
          routerLink: partnerAccountsNamedRoutes.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({
      ...defaultBaseStateData,
      breadcrumbItems: [],
    });
  }
}
