import { Injectable, inject } from '@angular/core';
import { Observable, map, of } from 'rxjs';
import { InventoryRecord, Offer, OfferLookupQuery } from '../models/offer.model';
import { OfferGateway } from './offer-gateway.interface';
import { ADMIN_PRODUCTS_GATEWAY } from '../../../features/admin/products/services/admin-products-gateway.token';
import { fromMajor } from '../../pricing/models/money.model';

/**
 * Derives Offers from the existing (mock) Products gateway - one offer per
 * product, sellerId defaulted to 'marketplace-owned' when absent, exactly
 * matching AdminProduct.sellerId's existing "absent means marketplace-owned"
 * convention. Real Offer/Product split (docs/backend/
 * PHASE-3-CATALOG-OFFER-FULFILLMENT-CONTRACT.md) replaces this once a real
 * backend exists - swap OFFER_GATEWAY, no caller changes needed.
 */
@Injectable({ providedIn: 'root' })
export class OfferLocalGateway implements OfferGateway {
  private readonly productsGateway = inject(ADMIN_PRODUCTS_GATEWAY);

  loadOffers(sellerId?: string): Observable<Offer[]> {
    return this.productsGateway.loadProducts({ search: '', page: 1, pageSize: 100 } as any).pipe(
      map((result: any) => (result.items ?? [])
        .map((p: any): Offer => this.toOffer(p))
        .filter((o: Offer) => !sellerId || o.sellerId === sellerId))
    );
  }

  lookup(query: OfferLookupQuery): Observable<Offer[]> {
    return this.loadOffers().pipe(
      map(offers => offers.filter(o =>
        (!query.sku || o.sellerSku === query.sku) &&
        (!query.sellerSku || o.sellerSku === query.sellerSku)
      ))
    );
  }

  loadInventory(offerId: string): Observable<InventoryRecord | null> {
    return of({ offerId, available: 42, reserved: 0, sold: 0, source: 'manual' });
  }

  publish(_offerId: string): Observable<{ ok: true } | { ok: false; errors: string[] }> {
    return of({ ok: true });
  }

  private toOffer(product: any): Offer {
    return {
      id: `offer_${product.id}`,
      marketplaceId: 'default',
      sellerId: product.sellerId ?? 'marketplace-owned',
      variantId: product.id,
      sellerSku: product.sku,
      price: fromMajor(product.price ?? 0, product.currency ?? 'RUB'),
      stockPolicy: 'track',
      status: product.visible ? 'published' : 'draft',
      executabilityChecked: !!product.visible,
    };
  }
}
