import { DomainError } from "../../shared/errors.ts";

export type InventoryStatus = "available" | "reserved" | "sold_funded" | "delivered" | "completed";

export interface InventoryItem {
  readonly id: string;
  readonly listingId: string;
  readonly sellerId: string;
  readonly secretCiphertext: Uint8Array;
  readonly secretFingerprint: string;
  status: InventoryStatus;
  orderId?: string;
  reservedUntil?: Date;
}

export interface InventoryRepository {
  reserveNext(listingId: string, orderId: string, reservedUntil: Date): Promise<InventoryItem | null>;
  findForOrder(orderId: string): Promise<InventoryItem | null>;
}

export class InventoryService {
  private readonly repository: InventoryRepository;
  constructor(repository: InventoryRepository) { this.repository = repository; }

  async reserve(listingId: string, orderId: string, now: Date, ttlMs = 15 * 60 * 1000): Promise<InventoryItem> {
    const prior = await this.repository.findForOrder(orderId);
    if (prior) return prior;
    const item = await this.repository.reserveNext(listingId, orderId, new Date(now.getTime() + ttlMs));
    if (!item) throw new DomainError("OUT_OF_STOCK", "No inventory is available.");
    return item;
  }
}
