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

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

import { environment } from '../../../environments/environment';
import { ICartAddOrUpdate, ICartModel } from '../interface/cart.interface';

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

  private subjectQty = new Subject<boolean>();

  getCartItems(): Observable<ICartModel> {
    return this.http.get<ICartModel>(`${environment.URL}/cart`);
  }

  addToCart(payload: ICartAddOrUpdate): Observable<ICartModel> {
    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<ICartModel>(`${environment.URL}/cart`, updatedPayload);
  }

  updateQty() {
    this.subjectQty.next(true);
  }

  getUpdateQtyClickEvent(): Observable<boolean> {
    return this.subjectQty.asObservable();
  }

  updateCart(payload: ICartAddOrUpdate): Observable<ICartModel> {
    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.put<ICartModel>(`${environment.URL}/cart`, updatedPayload);
  }

  replaceCart(payload: ICartAddOrUpdate): Observable<ICartModel> {
    return this.http.put<ICartModel>(`${environment.URL}/replace/cart`, payload);
  }

  deleteCart(id: number): Observable<number> {
    return this.http.delete<number>(`${environment.URL}/cart/${id}`);
  }

  clearCart() {
    return this.http.delete<number>(`${environment.URL}/clear/cart`);
  }

  syncCart(payload: ICartAddOrUpdate[]): Observable<ICartModel> {
    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<ICartModel>(`${environment.URL}/sync/cart`, updatedPayload);
  }
}
