import type { BigCommerceClient } from '../clients/bigcommerce.js';
import type { Cart, Checkout, CartLineItem } from '../types/index.js';

export function registerCartTools(client: BigCommerceClient) {
  return {
    // Cart Operations
    bigcommerce_create_cart: {
      description: 'Create a new cart (server-side cart, not storefront)',
      parameters: {
        type: 'object' as const,
        properties: {
          customer_id: { type: 'number', description: 'Customer ID (for logged-in customer)' },
          channel_id: { type: 'number', description: 'Channel ID (default: 1)' },
          line_items: {
            type: 'array',
            description: 'Array of line items to add',
            items: {
              type: 'object',
              properties: {
                quantity: { type: 'number', description: 'Quantity', required: true },
                product_id: { type: 'number', description: 'Product ID', required: true },
                variant_id: { type: 'number', description: 'Variant ID (if applicable)' },
                list_price: { type: 'number', description: 'Override list price' },
              },
            },
            required: true,
          },
          locale: { type: 'string', description: 'Locale code (e.g., en-US)' },
        },
        required: ['line_items'],
      },
      handler: async (params: Partial<Cart>) => {
        const result = await client.post<{ data: Cart }>('/carts', params);
        return result.data;
      },
    },

    bigcommerce_get_cart: {
      description: 'Get a cart by ID',
      parameters: {
        type: 'object' as const,
        properties: {
          cart_id: { type: 'string', description: 'Cart ID (UUID)', required: true },
          include: { type: 'string', description: 'Include additional data (redirect_urls, line_items.physical_items.options, line_items.digital_items.options)' },
        },
        required: ['cart_id'],
      },
      handler: async (params: { cart_id: string; include?: string }) => {
        const queryParams = params.include ? `?include=${params.include}` : '';
        const result = await client.get<{ data: Cart }>(`/carts/${params.cart_id}${queryParams}`);
        return result.data;
      },
    },

    bigcommerce_update_cart: {
      description: 'Update cart properties (customer_id, locale, etc.)',
      parameters: {
        type: 'object' as const,
        properties: {
          cart_id: { type: 'string', description: 'Cart ID (UUID)', required: true },
          customer_id: { type: 'number', description: 'Update customer ID' },
          locale: { type: 'string', description: 'Update locale' },
        },
        required: ['cart_id'],
      },
      handler: async (params: { cart_id: string; [key: string]: unknown }) => {
        const { cart_id, ...updateData } = params;
        const result = await client.put<{ data: Cart }>(`/carts/${cart_id}`, updateData);
        return result.data;
      },
    },

    bigcommerce_delete_cart: {
      description: 'Delete a cart',
      parameters: {
        type: 'object' as const,
        properties: {
          cart_id: { type: 'string', description: 'Cart ID (UUID)', required: true },
        },
        required: ['cart_id'],
      },
      handler: async (params: { cart_id: string }) => {
        await client.delete(`/carts/${params.cart_id}`);
        return { success: true, message: `Cart ${params.cart_id} deleted` };
      },
    },

    // Cart Line Items
    bigcommerce_add_cart_items: {
      description: 'Add line items to an existing cart',
      parameters: {
        type: 'object' as const,
        properties: {
          cart_id: { type: 'string', description: 'Cart ID (UUID)', required: true },
          line_items: {
            type: 'array',
            description: 'Array of line items to add',
            items: {
              type: 'object',
              properties: {
                quantity: { type: 'number', description: 'Quantity', required: true },
                product_id: { type: 'number', description: 'Product ID', required: true },
                variant_id: { type: 'number', description: 'Variant ID (if applicable)' },
              },
            },
            required: true,
          },
        },
        required: ['cart_id', 'line_items'],
      },
      handler: async (params: { cart_id: string; line_items: unknown[] }) => {
        const result = await client.post<{ data: Cart }>(`/carts/${params.cart_id}/items`, {
          line_items: params.line_items,
        });
        return result.data;
      },
    },

    bigcommerce_update_cart_item: {
      description: 'Update a line item in a cart (quantity, product_id)',
      parameters: {
        type: 'object' as const,
        properties: {
          cart_id: { type: 'string', description: 'Cart ID (UUID)', required: true },
          item_id: { type: 'string', description: 'Line item ID', required: true },
          line_item: {
            type: 'object',
            description: 'Updated line item data',
            required: true,
            properties: {
              quantity: { type: 'number', description: 'New quantity' },
              product_id: { type: 'number', description: 'Product ID' },
              variant_id: { type: 'number', description: 'Variant ID' },
            },
          },
        },
        required: ['cart_id', 'item_id', 'line_item'],
      },
      handler: async (params: { cart_id: string; item_id: string; line_item: unknown }) => {
        const result = await client.put<{ data: Cart }>(`/carts/${params.cart_id}/items/${params.item_id}`, {
          line_item: params.line_item,
        });
        return result.data;
      },
    },

    bigcommerce_delete_cart_item: {
      description: 'Delete a line item from a cart',
      parameters: {
        type: 'object' as const,
        properties: {
          cart_id: { type: 'string', description: 'Cart ID (UUID)', required: true },
          item_id: { type: 'string', description: 'Line item ID', required: true },
        },
        required: ['cart_id', 'item_id'],
      },
      handler: async (params: { cart_id: string; item_id: string }) => {
        const result = await client.delete<{ data: Cart }>(`/carts/${params.cart_id}/items/${params.item_id}`);
        return result.data;
      },
    },

    // Checkout Operations
    bigcommerce_create_checkout: {
      description: 'Create a checkout from a cart',
      parameters: {
        type: 'object' as const,
        properties: {
          cart_id: { type: 'string', description: 'Cart ID (UUID)', required: true },
        },
        required: ['cart_id'],
      },
      handler: async (params: { cart_id: string }) => {
        const result = await client.post<{ data: Checkout }>(`/checkouts/${params.cart_id}`, {});
        return result.data;
      },
    },

    bigcommerce_get_checkout: {
      description: 'Get checkout details',
      parameters: {
        type: 'object' as const,
        properties: {
          checkout_id: { type: 'string', description: 'Checkout ID (UUID)', required: true },
        },
        required: ['checkout_id'],
      },
      handler: async (params: { checkout_id: string }) => {
        const result = await client.get<{ data: Checkout }>(`/checkouts/${params.checkout_id}`);
        return result.data;
      },
    },

    bigcommerce_update_checkout: {
      description: 'Update checkout (billing address, shipping consignments, etc.)',
      parameters: {
        type: 'object' as const,
        properties: {
          checkout_id: { type: 'string', description: 'Checkout ID (UUID)', required: true },
          billing_address: {
            type: 'object',
            description: 'Billing address',
            properties: {
              first_name: { type: 'string' },
              last_name: { type: 'string' },
              email: { type: 'string' },
              address1: { type: 'string' },
              city: { type: 'string' },
              state_or_province: { type: 'string' },
              postal_code: { type: 'string' },
              country_code: { type: 'string' },
            },
          },
          customer_message: { type: 'string', description: 'Customer message/order notes' },
        },
        required: ['checkout_id'],
      },
      handler: async (params: { checkout_id: string; [key: string]: unknown }) => {
        const { checkout_id, ...updateData } = params;
        const result = await client.put<{ data: Checkout }>(`/checkouts/${checkout_id}`, updateData);
        return result.data;
      },
    },

    bigcommerce_add_checkout_billing_address: {
      description: 'Add or update billing address on checkout',
      parameters: {
        type: 'object' as const,
        properties: {
          checkout_id: { type: 'string', description: 'Checkout ID (UUID)', required: true },
          first_name: { type: 'string', description: 'First name', required: true },
          last_name: { type: 'string', description: 'Last name', required: true },
          email: { type: 'string', description: 'Email', required: true },
          address1: { type: 'string', description: 'Street address line 1', required: true },
          address2: { type: 'string', description: 'Street address line 2' },
          city: { type: 'string', description: 'City', required: true },
          state_or_province: { type: 'string', description: 'State/province', required: true },
          postal_code: { type: 'string', description: 'Postal code', required: true },
          country_code: { type: 'string', description: '2-letter country code', required: true },
          phone: { type: 'string', description: 'Phone number' },
        },
        required: ['checkout_id', 'first_name', 'last_name', 'email', 'address1', 'city', 'state_or_province', 'postal_code', 'country_code'],
      },
      handler: async (params: { checkout_id: string; [key: string]: unknown }) => {
        const { checkout_id, ...addressData } = params;
        const result = await client.post<{ data: Checkout }>(`/checkouts/${checkout_id}/billing-address`, addressData);
        return result.data;
      },
    },

    bigcommerce_add_checkout_consignment: {
      description: 'Add shipping consignment (shipping address + items) to checkout',
      parameters: {
        type: 'object' as const,
        properties: {
          checkout_id: { type: 'string', description: 'Checkout ID (UUID)', required: true },
          shipping_address: {
            type: 'object',
            description: 'Shipping address',
            required: true,
            properties: {
              first_name: { type: 'string', required: true },
              last_name: { type: 'string', required: true },
              email: { type: 'string', required: true },
              address1: { type: 'string', required: true },
              city: { type: 'string', required: true },
              state_or_province: { type: 'string', required: true },
              postal_code: { type: 'string', required: true },
              country_code: { type: 'string', required: true },
            },
          },
          line_items: {
            type: 'array',
            description: 'Line items for this consignment',
            required: true,
            items: {
              type: 'object',
              properties: {
                item_id: { type: 'string', description: 'Cart line item ID', required: true },
                quantity: { type: 'number', description: 'Quantity', required: true },
              },
            },
          },
        },
        required: ['checkout_id', 'shipping_address', 'line_items'],
      },
      handler: async (params: { checkout_id: string; [key: string]: unknown }) => {
        const { checkout_id, ...consignmentData } = params;
        const result = await client.post<{ data: Checkout }>(`/checkouts/${checkout_id}/consignments`, [consignmentData]);
        return result.data;
      },
    },

    bigcommerce_update_checkout_consignment: {
      description: 'Update a consignment (shipping address or line items)',
      parameters: {
        type: 'object' as const,
        properties: {
          checkout_id: { type: 'string', description: 'Checkout ID (UUID)', required: true },
          consignment_id: { type: 'string', description: 'Consignment ID', required: true },
          shipping_address: {
            type: 'object',
            description: 'Updated shipping address',
            properties: {
              first_name: { type: 'string' },
              last_name: { type: 'string' },
              address1: { type: 'string' },
              city: { type: 'string' },
              state_or_province: { type: 'string' },
              postal_code: { type: 'string' },
              country_code: { type: 'string' },
            },
          },
          line_items: {
            type: 'array',
            description: 'Updated line items',
            items: {
              type: 'object',
              properties: {
                item_id: { type: 'string' },
                quantity: { type: 'number' },
              },
            },
          },
        },
        required: ['checkout_id', 'consignment_id'],
      },
      handler: async (params: { checkout_id: string; consignment_id: string; [key: string]: unknown }) => {
        const { checkout_id, consignment_id, ...updateData } = params;
        const result = await client.put<{ data: Checkout }>(`/checkouts/${checkout_id}/consignments/${consignment_id}`, updateData);
        return result.data;
      },
    },

    bigcommerce_delete_checkout_consignment: {
      description: 'Delete a consignment from checkout',
      parameters: {
        type: 'object' as const,
        properties: {
          checkout_id: { type: 'string', description: 'Checkout ID (UUID)', required: true },
          consignment_id: { type: 'string', description: 'Consignment ID', required: true },
        },
        required: ['checkout_id', 'consignment_id'],
      },
      handler: async (params: { checkout_id: string; consignment_id: string }) => {
        const result = await client.delete<{ data: Checkout }>(`/checkouts/${params.checkout_id}/consignments/${params.consignment_id}`);
        return result.data;
      },
    },

    bigcommerce_create_checkout_order: {
      description: 'Complete checkout and create an order',
      parameters: {
        type: 'object' as const,
        properties: {
          checkout_id: { type: 'string', description: 'Checkout ID (UUID)', required: true },
        },
        required: ['checkout_id'],
      },
      handler: async (params: { checkout_id: string }) => {
        const result = await client.post<{ data: { id: number } }>(`/checkouts/${params.checkout_id}/orders`, {});
        return result.data;
      },
    },

    // Cart Redirects (for headless storefronts)
    bigcommerce_create_cart_redirect_url: {
      description: 'Generate a redirect URL for cart (to embedded checkout or full checkout)',
      parameters: {
        type: 'object' as const,
        properties: {
          cart_id: { type: 'string', description: 'Cart ID (UUID)', required: true },
        },
        required: ['cart_id'],
      },
      handler: async (params: { cart_id: string }) => {
        const result = await client.post<{ cart_url: string; checkout_url: string; embedded_checkout_url: string }>(
          `/carts/${params.cart_id}/redirect_urls`,
          {}
        );
        return result;
      },
    },
  };
}
