import { z } from 'zod';
import { ShopifyClient } from '../clients/shopify.js';

const ListOrdersInput = z.object({
  limit: z.number().min(1).max(250).default(50).describe('Results per page'),
  page_info: z.string().optional().describe('Cursor for pagination'),
  status: z.enum(['open', 'archived', 'cancelled', 'any']).optional().describe('Filter by order status'),
  financial_status: z.enum(['pending', 'authorized', 'partially_paid', 'paid', 'partially_refunded', 'refunded', 'voided', 'any']).optional().describe('Filter by financial status'),
  fulfillment_status: z.enum(['shipped', 'partial', 'unshipped', 'any', 'unfulfilled']).optional().describe('Filter by fulfillment status'),
  created_at_min: z.string().optional().describe('Filter by min creation date (ISO 8601)'),
  created_at_max: z.string().optional().describe('Filter by max creation date (ISO 8601)'),
  updated_at_min: z.string().optional().describe('Filter by min update date (ISO 8601)'),
  fields: z.string().optional().describe('Comma-separated list of fields to retrieve'),
});

const GetOrderInput = z.object({
  id: z.string().describe('Order ID'),
  fields: z.string().optional().describe('Comma-separated list of fields to retrieve'),
});

const CreateOrderInput = z.object({
  line_items: z.array(z.object({
    variant_id: z.string().optional().describe('Product variant ID'),
    quantity: z.number().describe('Quantity'),
    price: z.string().optional().describe('Price override'),
    title: z.string().optional().describe('Line item title (if no variant_id)'),
  })).describe('Order line items'),
  customer: z.object({
    id: z.string().optional().describe('Existing customer ID'),
    email: z.string().optional().describe('Customer email'),
    first_name: z.string().optional().describe('Customer first name'),
    last_name: z.string().optional().describe('Customer last name'),
  }).optional().describe('Customer information'),
  billing_address: z.object({
    address1: z.string().optional().describe('Address line 1'),
    city: z.string().optional().describe('City'),
    province: z.string().optional().describe('State/Province'),
    country: z.string().optional().describe('Country'),
    zip: z.string().optional().describe('Postal code'),
  }).optional().describe('Billing address'),
  shipping_address: z.object({
    address1: z.string().optional().describe('Address line 1'),
    city: z.string().optional().describe('City'),
    province: z.string().optional().describe('State/Province'),
    country: z.string().optional().describe('Country'),
    zip: z.string().optional().describe('Postal code'),
  }).optional().describe('Shipping address'),
  financial_status: z.enum(['pending', 'authorized', 'paid']).optional().describe('Financial status'),
  send_receipt: z.boolean().optional().describe('Send order confirmation to customer'),
  note: z.string().optional().describe('Order note'),
});

const UpdateOrderInput = z.object({
  id: z.string().describe('Order ID'),
  note: z.string().optional().describe('Order note'),
  tags: z.string().optional().describe('Comma-separated tags'),
  email: z.string().optional().describe('Customer email'),
});

const CancelOrderInput = z.object({
  id: z.string().describe('Order ID'),
  amount: z.number().optional().describe('Amount to refund'),
  restock: z.boolean().optional().describe('Restock items'),
  reason: z.enum(['customer', 'fraud', 'inventory', 'declined', 'other']).optional().describe('Cancellation reason'),
  email: z.boolean().optional().describe('Send notification email'),
});

const CloseOrderInput = z.object({
  id: z.string().describe('Order ID'),
});

export default [
    {
      name: 'shopify_list_orders',
      description: 'List orders with pagination and filtering by status, financial status, fulfillment status, and date ranges',
      inputSchema: {
        type: 'object' as const,
        properties: {
          limit: { type: 'number', description: 'Results per page', default: 50, minimum: 1, maximum: 250 },
          page_info: { type: 'string', description: 'Cursor for pagination' },
          status: { type: 'string', enum: ['open', 'archived', 'cancelled', 'any'], description: 'Filter by order status' },
          financial_status: { type: 'string', enum: ['pending', 'authorized', 'partially_paid', 'paid', 'partially_refunded', 'refunded', 'voided', 'any'], description: 'Filter by financial status' },
          fulfillment_status: { type: 'string', enum: ['shipped', 'partial', 'unshipped', 'any', 'unfulfilled'], description: 'Filter by fulfillment status' },
          created_at_min: { type: 'string', description: 'Filter by min creation date (ISO 8601)' },
          created_at_max: { type: 'string', description: 'Filter by max creation date (ISO 8601)' },
          updated_at_min: { type: 'string', description: 'Filter by min update date (ISO 8601)' },
          fields: { type: 'string', description: 'Comma-separated list of fields to retrieve' },
        },
      },
      handler: async (input: unknown, client: ShopifyClient) => {
        const validated = ListOrdersInput.parse(input);
        const results = await client.list('/orders.json', { params: validated });
        return {
          content: [{ type: 'text' as const, text: JSON.stringify(results, null, 2) }],
        };
      },
    },
    {
      name: 'shopify_get_order',
      description: 'Get a specific order by ID with optional field filtering',
      inputSchema: {
        type: 'object' as const,
        properties: {
          id: { type: 'string', description: 'Order ID' },
          fields: { type: 'string', description: 'Comma-separated list of fields to retrieve' },
        },
        required: ['id'],
      },
      handler: async (input: unknown, client: ShopifyClient) => {
        const validated = GetOrderInput.parse(input);
        const result = await client.get(`/orders/${validated.id}.json`, {
          params: validated.fields ? { fields: validated.fields } : {},
        });
        return {
          content: [{ type: 'text' as const, text: JSON.stringify(result, null, 2) }],
        };
      },
    },
    {
      name: 'shopify_create_order',
      description: 'Create a new order with line items, customer, and addresses',
      inputSchema: {
        type: 'object' as const,
        properties: {
          line_items: {
            type: 'array',
            description: 'Order line items',
            items: {
              type: 'object',
              properties: {
                variant_id: { type: 'string', description: 'Product variant ID' },
                quantity: { type: 'number', description: 'Quantity' },
                price: { type: 'string', description: 'Price override' },
                title: { type: 'string', description: 'Line item title (if no variant_id)' },
              },
            },
          },
          customer: {
            type: 'object',
            description: 'Customer information',
            properties: {
              id: { type: 'string', description: 'Existing customer ID' },
              email: { type: 'string', description: 'Customer email' },
              first_name: { type: 'string', description: 'Customer first name' },
              last_name: { type: 'string', description: 'Customer last name' },
            },
          },
          billing_address: {
            type: 'object',
            description: 'Billing address',
            properties: {
              address1: { type: 'string', description: 'Address line 1' },
              city: { type: 'string', description: 'City' },
              province: { type: 'string', description: 'State/Province' },
              country: { type: 'string', description: 'Country' },
              zip: { type: 'string', description: 'Postal code' },
            },
          },
          shipping_address: {
            type: 'object',
            description: 'Shipping address',
            properties: {
              address1: { type: 'string', description: 'Address line 1' },
              city: { type: 'string', description: 'City' },
              province: { type: 'string', description: 'State/Province' },
              country: { type: 'string', description: 'Country' },
              zip: { type: 'string', description: 'Postal code' },
            },
          },
          financial_status: { type: 'string', enum: ['pending', 'authorized', 'paid'], description: 'Financial status' },
          send_receipt: { type: 'boolean', description: 'Send order confirmation to customer' },
          note: { type: 'string', description: 'Order note' },
        },
        required: ['line_items'],
      },
      handler: async (input: unknown, client: ShopifyClient) => {
        const validated = CreateOrderInput.parse(input);
        const result = await client.create('/orders.json', { order: validated });
        return {
          content: [{ type: 'text' as const, text: JSON.stringify(result, null, 2) }],
        };
      },
    },
    {
      name: 'shopify_update_order',
      description: 'Update an existing order (limited fields: note, tags, email)',
      inputSchema: {
        type: 'object' as const,
        properties: {
          id: { type: 'string', description: 'Order ID' },
          note: { type: 'string', description: 'Order note' },
          tags: { type: 'string', description: 'Comma-separated tags' },
          email: { type: 'string', description: 'Customer email' },
        },
        required: ['id'],
      },
      handler: async (input: unknown, client: ShopifyClient) => {
        const validated = UpdateOrderInput.parse(input);
        const { id, ...updates } = validated;
        const result = await client.update(`/orders/${id}.json`, { order: updates });
        return {
          content: [{ type: 'text' as const, text: JSON.stringify(result, null, 2) }],
        };
      },
    },
    {
      name: 'shopify_cancel_order',
      description: 'Cancel an order with optional refund and restocking',
      inputSchema: {
        type: 'object' as const,
        properties: {
          id: { type: 'string', description: 'Order ID' },
          amount: { type: 'number', description: 'Amount to refund' },
          restock: { type: 'boolean', description: 'Restock items' },
          reason: { type: 'string', enum: ['customer', 'fraud', 'inventory', 'declined', 'other'], description: 'Cancellation reason' },
          email: { type: 'boolean', description: 'Send notification email' },
        },
        required: ['id'],
      },
      handler: async (input: unknown, client: ShopifyClient) => {
        const validated = CancelOrderInput.parse(input);
        const { id, ...params } = validated;
        const result = await client.create(`/orders/${id}/cancel.json`, params);
        return {
          content: [{ type: 'text' as const, text: JSON.stringify(result, null, 2) }],
        };
      },
    },
    {
      name: 'shopify_close_order',
      description: 'Close an order (mark as complete)',
      inputSchema: {
        type: 'object' as const,
        properties: {
          id: { type: 'string', description: 'Order ID' },
        },
        required: ['id'],
      },
      handler: async (input: unknown, client: ShopifyClient) => {
        const validated = CloseOrderInput.parse(input);
        const result = await client.create(`/orders/${validated.id}/close.json`, {});
        return {
          content: [{ type: 'text' as const, text: JSON.stringify(result, null, 2) }],
        };
      },
    },
  ];
