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

export interface PurchaseSummary {
  id: string;
  total: number;
  status: string;
  disputed?: boolean;
  is_delayed?: boolean;
  order_count: number;
  created_at: string;
}

export interface PurchaseDetail {
  id: string;
  buyer_id: string;
  subtotal: number;
  discount_total: number;
  shipping_total: number;
  tax_total: number;
  total: number;
  status: string;
  disputed?: boolean;
  is_delayed?: boolean;
  shipping_address: {
    first_name: string;
    last_name: string;
    street: string;
    city: string;
    state: string;
    zip: string;
  };
  orders: OrderDetail[];
  created_at: string;
}

export interface OrderDetail {
  id: string;
  store: { id: string; name: string };
  buyer?: { first_name: string | null; last_name: string | null } | null;
  shipping_address?: {
    street: string | null;
    city: string | null;
    state: string | null;
    zip: string | null;
  } | null;
  subtotal: number;
  shipping_cost: number;
  seller_payout?: number;
  status: string;
  tracking_number?: string | null;
  tracking_url?: string | null;
  carrier?: string | null;
  service?: string | null;
  shipping_label_url?: string | null;
  label_purchased_at?: string | null;
  ship_by?: string | null;
  shipped_at?: string | null;
  delivered_at?: string | null;
  cancelled_by?: string | null;
  cancellation_reason?: string | null;
  cancelled_at?: string | null;
  stripe_refund_id?: string | null;
  stripe_transfer_id?: string | null;
  /** Derived: 'succeeded' when refund persisted with a Stripe id,
   *  'pending_reconciliation' when cancellation persisted but Stripe failed,
   *  'not_required' for non-cancelled orders. */
  refund_status?: 'succeeded' | 'pending_reconciliation' | 'not_required';
  /** Derived: same shape as refund_status but for the seller-payout transfer. */
  transfer_status?: 'succeeded' | 'pending_reconciliation' | 'not_required';
  is_delayed?: boolean;
  open_return_id?: string | null;
  returns_open_until?: string | null;
  items: OrderItemData[];
  created_at: string;
}

export interface OrderItemData {
  id: string;
  item_id: string;
  title_snapshot: string;
  price_snapshot: number;
  image_url_snapshot: string | null;
}

export interface LabelRateOption {
  id: string;
  carrier: string;
  service: string;
  amount_cents: number;
  estimated_days?: number | null;
}

export function createPurchaseEndpoints(client: AlqoveClient) {
  return {
    list(params?: Record<string, string>) {
      return client.get<PaginatedResponse<PurchaseSummary>>('/v1/purchases', params);
    },

    get(purchaseId: string) {
      return client.get<ApiResponse<PurchaseDetail>>(`/v1/purchases/${purchaseId}`);
    },
  };
}
