import { HttpClient } from '@angular/common/http';
import { inject, Injectable } from '@angular/core';

import { Store } from '@ngxs/store';
import { Observable } from 'rxjs';

import { environment } from '../../../environments/environment';
import { Params } from '../interface/core.interface';
import {
  ICheckoutPayload,
  IOrder,
  IOrderCheckout,
  IOrderModel,
  IPlaceOrder,
  IRePaymentPayload,
} from '../interface/order.interface';

@Injectable({
  providedIn: 'root',
})
export class OrderService {
  private store = inject(Store);
  private http = inject(HttpClient);

  public skeletonLoader: boolean = false;

  getOrders(payload?: Params): Observable<IOrderModel> {
    return this.http.get<IOrderModel>(`${environment.URL}/order`, { params: payload });
  }

  viewOrder(id: number): Observable<IOrder> {
    return this.http.get<IOrder>(`${environment.URL}/order/${id}`);
  }

  checkout(payload: ICheckoutPayload): Observable<IOrderCheckout> {
    const is_zone = this.store.selectSnapshot(
      state => state?.setting?.setting?.activation?.zone_enable,
    );
    const zone = this.store.selectSnapshot(state => state.zone.selectedZone);
    const updatedPayload = {
      ...payload,
      ...(is_zone && Array.isArray(zone) ? { zone_ids: zone } : {}), // Ensure zone is an array
    };
    return this.http.post<IOrderCheckout>(`${environment.URL}/checkout`, updatedPayload);
  }

  placeOrder(payload: ICheckoutPayload): Observable<IPlaceOrder> {
    const is_zone = this.store.selectSnapshot(
      state => state?.setting?.setting?.activation?.zone_enable,
    );
    const zone = this.store.selectSnapshot(state => state.zone.selectedZone);
    const updatedPayload = {
      ...payload,
      ...(is_zone && { zone_ids: zone }), // Include zone_ids only if is_zone is true
    };
    return this.http.post<IPlaceOrder>(`${environment.URL}/order`, updatedPayload);
  }

  rePayment(payload: IRePaymentPayload): Observable<IPlaceOrder> {
    return this.http.post<IPlaceOrder>(`${environment.URL}/rePayment`, payload);
  }

  orderTracking(payload: { order_number: string; email_or_phone: string }): Observable<IOrder> {
    return this.http.get<IOrder>(`${environment.URL}/trackOrder`, { params: payload });
  }

  downloadInvoice(payload?: Params): Observable<Blob> {
    return this.http.post<Blob>(`${environment.URL}/order/invoice`, payload, {
      responseType: 'blob' as 'json',
    });
  }
}
