import { Injectable } from '@angular/core';
import { Observable, of } from 'rxjs';
import { CheckoutSession, ServerCart, ServerCartLine } from '../models/server-cart.model';
import { ServerCartGateway } from './server-cart-gateway.interface';

const CART_TTL_MS = 30 * 24 * 60 * 60 * 1000;

/**
 * In-memory stand-in for the server cart. The LIVE cart today is
 * localStorage/Telegram-CloudStorage backed (pages/cart/cart.component.ts,
 * services/cart.service.ts) and deliberately untouched by this module - see
 * docs/backend/PHASE-6-CART-CHECKOUT-CONTRACT.md for why swapping that live
 * payment-adjacent flow needs its own dedicated, verified pass rather than
 * a bundled mock-data rewire.
 */
@Injectable({ providedIn: 'root' })
export class ServerCartLocalGateway implements ServerCartGateway {
  private cart: ServerCart = {
    id: 'cart_local',
    marketplaceId: 'default',
    sessionToken: 'local-session',
    createdAt: new Date().toISOString(),
    expiresAt: new Date(Date.now() + CART_TTL_MS).toISOString(),
  };
  private lines: ServerCartLine[] = [];

  getCart(): Observable<{ cart: ServerCart; lines: ServerCartLine[] }> {
    return of({ cart: this.cart, lines: this.lines });
  }

  addLine(offerId: string, qty: number): Observable<ServerCartLine> {
    const existing = this.lines.find(l => l.offerId === offerId);
    if (existing) {
      existing.qty += qty;
      return of(existing);
    }
    const line: ServerCartLine = { id: `line_${Date.now()}`, cartId: this.cart.id, offerId, qty, addedAt: new Date().toISOString() };
    this.lines.push(line);
    return of(line);
  }

  updateLine(lineId: string, qty: number): Observable<ServerCartLine> {
    const line = this.lines.find(l => l.id === lineId);
    if (line) {
      line.qty = qty;
    }
    return of(line as ServerCartLine);
  }

  removeLine(lineId: string): Observable<void> {
    this.lines = this.lines.filter(l => l.id !== lineId);
    return of(void 0);
  }

  startCheckout(deliveryOptionId: string, _currency: string): Observable<CheckoutSession> {
    return of({
      id: `chk_${Date.now()}`,
      cartId: this.cart.id,
      customerContact: { verified: false },
      deliveryOptionId,
      status: 'open',
      createdAt: new Date().toISOString(),
      expiresAt: new Date(Date.now() + 15 * 60 * 1000).toISOString(),
    });
  }
}
