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

interface ConsumerCustomerState extends EntityState<ICustomerResponse> {
  breadcrumbItems: MenuItem[];
}

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

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

  private setBreadcrumb(customerId: string) {
    this.patchState({
      breadcrumbItems: [
        {
          ...consumerCustomersNamedRoutes.customers.meta,
          routerLink: consumerCustomersNamedRoutes.customers.meta.pagePath!(),
        },
        {
          title:
            this.entity()?.type === 'LEGAL'
              ? this.entity()?.legal!.company_name
              : `${this.entity()?.individual!.first_name} ${this.entity()?.individual!.last_name}`,
          routerLink: consumerCustomersNamedRoutes.customer.meta.pagePath!(customerId),
        },
      ],
    });
  }

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

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