import type {
  CheckoutIntentGuestBody,
  CreateGuestPurchaseBody,
  CreateGuestPurchaseResponse,
  CreatePurchaseBody,
  CreatePurchaseResponse,
  ListPurchasesResponse,
} from '@/server/schemas/purchase';
import type { CheckoutIntentData } from '@/server/domain/checkout/types';
import type {
  JoinGroupDealBody,
  JoinGroupDealGuestBody,
  ReserveResponse,
} from '@/server/schemas/group-deal';
import type {
  CreatePaymentMethodBody,
  CreatePaymentMethodResponse,
} from '@/server/schemas/payment-method';
import type {
  ApproveRefundBody,
  RefundApproveResponse,
  ExecuteRefundBody,
  RefundExecuteResponse,
} from '@/server/schemas/refund';
import type { ApiContract } from '@/lib/api/typed-client';

type ApiError = {
  ok: false;
  error: string;
  code?: string;
};

type PurchaseSuccess = CreatePurchaseResponse & {
  dealTitle?: string;
  businessName?: string;
  amountPaid?: string;
  purchaseCount?: number;
  totalSavings?: number;
};

type GuestPurchaseSuccess = CreateGuestPurchaseResponse & {
  dealTitle?: string;
  businessName?: string;
  amountPaid?: string;
};

type PaymentMethodsResponse =
  | {
      ok: true;
      methods: Array<{
        id: string;
        brand: string;
        last4: string;
        isDefault: boolean;
      }>;
    }
  | ApiError;

export const marketplaceApiContract = {
  '/api/payment-methods': {
    GET: {
      response: {} as PaymentMethodsResponse,
    },
    POST: {
      body: {} as CreatePaymentMethodBody,
      response: {} as CreatePaymentMethodResponse | ApiError,
    },
  },
  '/api/purchases': {
    GET: {
      response: {} as ListPurchasesResponse | ApiError,
    },
    POST: {
      body: {} as CreatePurchaseBody,
      response: {} as PurchaseSuccess | ApiError,
    },
  },
  '/api/purchases/guest': {
    POST: {
      body: {} as CreateGuestPurchaseBody,
      response: {} as GuestPurchaseSuccess | ApiError,
    },
  },
  '/api/checkout/intent-guest': {
    POST: {
      body: {} as CheckoutIntentGuestBody,
      response: {} as { ok: true; data: CheckoutIntentData } | ApiError,
    },
  },
  '/api/group-deals/:id/reserve': {
    POST: {
      params: {} as { id: string },
      body: {} as JoinGroupDealBody,
      response: {} as ReserveResponse | ApiError,
    },
  },
  '/api/group-deals/:id/reserve-guest': {
    POST: {
      params: {} as { id: string },
      body: {} as JoinGroupDealGuestBody,
      response: {} as ReserveResponse | ApiError,
    },
  },
  '/api/refunds/:id/approve': {
    POST: {
      params: {} as { id: string },
      body: {} as ApproveRefundBody,
      response: {} as RefundApproveResponse | ApiError,
    },
  },
  '/api/refunds/:id/execute': {
    POST: {
      params: {} as { id: string },
      body: {} as ExecuteRefundBody,
      response: {} as RefundExecuteResponse | ApiError,
    },
  },
} satisfies ApiContract;
