import { HttpClient } from '@angular/common/http';
import { Injectable, inject } from '@angular/core';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { CheckoutSession, ServerCart, ServerCartLine } from '../models/server-cart.model';
import { ServerCartGateway } from './server-cart-gateway.interface';

/** Contract: docs/backend/PHASE-6-CART-CHECKOUT-CONTRACT.md §3, §5. */
@Injectable({ providedIn: 'root' })
export class ServerCartApiGateway implements ServerCartGateway {
  private readonly http = inject(HttpClient);

  getCart(): Observable<{ cart: ServerCart; lines: ServerCartLine[] }> {
    return this.http.get<{ cart: ServerCart; lines: ServerCartLine[] }>('/api/v2/storefront/cart');
  }

  addLine(offerId: string, qty: number): Observable<ServerCartLine> {
    return this.http.post<ServerCartLine>('/api/v2/storefront/cart/lines', { offerId, qty });
  }

  updateLine(lineId: string, qty: number): Observable<ServerCartLine> {
    return this.http.patch<ServerCartLine>(`/api/v2/storefront/cart/lines/${encodeURIComponent(lineId)}`, { qty });
  }

  removeLine(lineId: string): Observable<void> {
    return this.http
      .delete(`/api/v2/storefront/cart/lines/${encodeURIComponent(lineId)}`)
      .pipe(map(() => undefined));
  }

  startCheckout(deliveryOptionId: string, currency: string): Observable<CheckoutSession> {
    // §5 example body is { cartId, currency, deliveryOptionId } - cartId is
    // implicit server-side (the session's own cart), so it is not sent here.
    return this.http.post<CheckoutSession>('/api/v2/storefront/checkout', { currency, deliveryOptionId });
  }
}
