import type { ApiResponse } from '@alqove/types';
import type { AlqoveClient } from '../client';

export interface ShippingAddress {
  first_name: string;
  last_name: string;
  street: string;
  city: string;
  state: string;
  zip: string;
}

export interface CheckoutData {
  checkout_id: string;
  client_secret: string;
  stores: CheckoutStoreGroup[];
  subtotal: number;
  discount_total: number;
  shipping_total: number;
  tax_total: number;
  total: number;
}

export interface CheckoutStoreGroup {
  store: { id: string; name: string };
  items: { id: string; title: string; price: number }[];
  subtotal: number;
  shipping: number;
}

export interface CheckoutConflict {
  error: string;
  unavailable_items: { id: string; title: string; reason: string }[];
  available_items: { id: string; title: string; price: number }[];
  updated_totals: { subtotal: number; shipping_total: number; total: number };
}

export function createCheckoutEndpoints(client: AlqoveClient) {
  return {
    initiate(shippingAddress: ShippingAddress, excludedItemIds: string[] = []) {
      return client.post<ApiResponse<CheckoutData>>('/v1/checkout', {
        shipping_address: shippingAddress,
        excluded_item_ids: excludedItemIds,
      });
    },

    cancel(checkoutId: string) {
      return client.delete<void>(`/v1/checkout/${checkoutId}`);
    },
  };
}
