import { inject, Injectable } from '@angular/core';
import { ShippingAddressService as GeneratedShippingAddressService } from '@generated/swagger/crm-api';
import {
  FetchCustomerShippingAddressesInput,
  FetchCustomerShippingAddressesSchema,
  FetchShippingAddressInput,
  FetchShippingAddressSchema,
  ShippingAddress,
} from '../schemas';
import {
  catchResponseArgsErrorPipe,
  ListResponseArgs,
  ResponseArgs,
  takeUntilAborted,
} from '@isa/common/data-access';
import { firstValueFrom } from 'rxjs';
import { logger } from '@isa/core/logging';

@Injectable({ providedIn: 'root' })
export class ShippingAddressService {
  #shippingAddressService = inject(GeneratedShippingAddressService);
  #logger = logger(() => ({
    service: 'ShippingAddressService',
  }));

  async fetchCustomerShippingAddresses(
    params: FetchCustomerShippingAddressesInput,
    abortSignal?: AbortSignal,
  ): Promise<ListResponseArgs<ShippingAddress>> {
    this.#logger.info('Fetching customer shipping addresses from API');
    const { customerId, take, skip } =
      FetchCustomerShippingAddressesSchema.parse(params);

    let req$ = this.#shippingAddressService
      .ShippingAddressGetShippingAddresses({ customerId, take, skip })
      .pipe(catchResponseArgsErrorPipe());

    if (abortSignal) {
      req$ = req$.pipe(takeUntilAborted(abortSignal));
    }

    try {
      const res = await firstValueFrom(req$);
      this.#logger.debug('Successfully fetched customer shipping addresses');
      return res as ListResponseArgs<ShippingAddress>;
    } catch (error) {
      this.#logger.error('Error fetching customer shipping addresses', error);
      return {
        result: [],
        totalCount: 0,
      } as unknown as ListResponseArgs<ShippingAddress>;
    }
  }

  async fetchShippingAddress(
    params: FetchShippingAddressInput,
    abortSignal?: AbortSignal,
  ): Promise<ResponseArgs<ShippingAddress>> {
    this.#logger.info('Fetching shipping address from API');
    const { shippingAddressId } = FetchShippingAddressSchema.parse(params);

    let req$ = this.#shippingAddressService
      .ShippingAddressGetShippingaddress(shippingAddressId)
      .pipe(catchResponseArgsErrorPipe());

    if (abortSignal) {
      req$ = req$.pipe(takeUntilAborted(abortSignal));
    }

    try {
      const res = await firstValueFrom(req$);
      this.#logger.debug('Successfully fetched shipping address');
      return res as ResponseArgs<ShippingAddress>;
    } catch (error) {
      this.#logger.error('Error fetching shipping address', error);
      return undefined as unknown as ResponseArgs<ShippingAddress>;
    }
  }
}
