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

const ListPriceRulesInput = z.object({
  limit: z.number().min(1).max(250).default(50).describe('Results per page'),
  page_info: z.string().optional().describe('Cursor for pagination'),
});

const GetPriceRuleInput = z.object({
  id: z.string().describe('Price rule ID'),
});

const CreatePriceRuleInput = z.object({
  title: z.string().describe('Price rule title'),
  target_type: z.enum(['line_item', 'shipping_line']).describe('What the price rule applies to'),
  target_selection: z.enum(['all', 'entitled']).describe('Which items the rule applies to'),
  allocation_method: z.enum(['across', 'each']).describe('How the discount is distributed'),
  value_type: z.enum(['fixed_amount', 'percentage']).describe('Type of discount value'),
  value: z.string().describe('Discount value (e.g., "-10.0" for $10 off or "-15.0" for 15% off)'),
  customer_selection: z.enum(['all', 'prerequisite']).describe('Which customers the rule applies to'),
  starts_at: z.string().describe('Start date/time (ISO 8601)'),
  ends_at: z.string().optional().describe('End date/time (ISO 8601)'),
  usage_limit: z.number().optional().describe('Maximum number of times this discount can be used'),
  once_per_customer: z.boolean().optional().describe('Limit to one use per customer'),
});

const UpdatePriceRuleInput = z.object({
  id: z.string().describe('Price rule ID'),
  title: z.string().optional().describe('Price rule title'),
  value: z.string().optional().describe('Discount value'),
  starts_at: z.string().optional().describe('Start date/time (ISO 8601)'),
  ends_at: z.string().optional().describe('End date/time (ISO 8601)'),
  usage_limit: z.number().optional().describe('Maximum number of times this discount can be used'),
});

const DeletePriceRuleInput = z.object({
  id: z.string().describe('Price rule ID'),
});

const ListDiscountCodesInput = z.object({
  price_rule_id: z.string().describe('Price rule ID'),
  limit: z.number().min(1).max(250).default(50).describe('Results per page'),
  page_info: z.string().optional().describe('Cursor for pagination'),
});

const CreateDiscountCodeInput = z.object({
  price_rule_id: z.string().describe('Price rule ID'),
  code: z.string().describe('Discount code'),
  usage_count: z.number().optional().describe('Number of times this code has been used'),
});

export default [
    {
      name: 'shopify_list_price_rules',
      description: 'List all price rules (discount rules)',
      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' },
        },
      },
      handler: async (input: unknown, client: ShopifyClient) => {
        const validated = ListPriceRulesInput.parse(input);
        const results = await client.list('/price_rules.json', { params: validated });
        return {
          content: [{ type: 'text' as const, text: JSON.stringify(results, null, 2) }],
        };
      },
    },
    {
      name: 'shopify_get_price_rule',
      description: 'Get a specific price rule by ID',
      inputSchema: {
        type: 'object' as const,
        properties: {
          id: { type: 'string', description: 'Price rule ID' },
        },
        required: ['id'],
      },
      handler: async (input: unknown, client: ShopifyClient) => {
        const validated = GetPriceRuleInput.parse(input);
        const result = await client.get(`/price_rules/${validated.id}.json`);
        return {
          content: [{ type: 'text' as const, text: JSON.stringify(result, null, 2) }],
        };
      },
    },
    {
      name: 'shopify_create_price_rule',
      description: 'Create a new price rule (discount rule)',
      inputSchema: {
        type: 'object' as const,
        properties: {
          title: { type: 'string', description: 'Price rule title' },
          target_type: { type: 'string', enum: ['line_item', 'shipping_line'], description: 'What the price rule applies to' },
          target_selection: { type: 'string', enum: ['all', 'entitled'], description: 'Which items the rule applies to' },
          allocation_method: { type: 'string', enum: ['across', 'each'], description: 'How the discount is distributed' },
          value_type: { type: 'string', enum: ['fixed_amount', 'percentage'], description: 'Type of discount value' },
          value: { type: 'string', description: 'Discount value (e.g., "-10.0" for $10 off or "-15.0" for 15% off)' },
          customer_selection: { type: 'string', enum: ['all', 'prerequisite'], description: 'Which customers the rule applies to' },
          starts_at: { type: 'string', description: 'Start date/time (ISO 8601)' },
          ends_at: { type: 'string', description: 'End date/time (ISO 8601)' },
          usage_limit: { type: 'number', description: 'Maximum number of times this discount can be used' },
          once_per_customer: { type: 'boolean', description: 'Limit to one use per customer' },
        },
        required: ['title', 'target_type', 'target_selection', 'allocation_method', 'value_type', 'value', 'customer_selection', 'starts_at'],
      },
      handler: async (input: unknown, client: ShopifyClient) => {
        const validated = CreatePriceRuleInput.parse(input);
        const result = await client.create('/price_rules.json', { price_rule: validated });
        return {
          content: [{ type: 'text' as const, text: JSON.stringify(result, null, 2) }],
        };
      },
    },
    {
      name: 'shopify_update_price_rule',
      description: 'Update an existing price rule',
      inputSchema: {
        type: 'object' as const,
        properties: {
          id: { type: 'string', description: 'Price rule ID' },
          title: { type: 'string', description: 'Price rule title' },
          value: { type: 'string', description: 'Discount value' },
          starts_at: { type: 'string', description: 'Start date/time (ISO 8601)' },
          ends_at: { type: 'string', description: 'End date/time (ISO 8601)' },
          usage_limit: { type: 'number', description: 'Maximum number of times this discount can be used' },
        },
        required: ['id'],
      },
      handler: async (input: unknown, client: ShopifyClient) => {
        const validated = UpdatePriceRuleInput.parse(input);
        const { id, ...updates } = validated;
        const result = await client.update(`/price_rules/${id}.json`, { price_rule: updates });
        return {
          content: [{ type: 'text' as const, text: JSON.stringify(result, null, 2) }],
        };
      },
    },
    {
      name: 'shopify_delete_price_rule',
      description: 'Delete a price rule by ID',
      inputSchema: {
        type: 'object' as const,
        properties: {
          id: { type: 'string', description: 'Price rule ID' },
        },
        required: ['id'],
      },
      handler: async (input: unknown, client: ShopifyClient) => {
        const validated = DeletePriceRuleInput.parse(input);
        await client.delete(`/price_rules/${validated.id}.json`);
        return {
          content: [{ type: 'text' as const, text: `Price rule ${validated.id} deleted successfully` }],
        };
      },
    },
    {
      name: 'shopify_list_discount_codes',
      description: 'List discount codes for a specific price rule',
      inputSchema: {
        type: 'object' as const,
        properties: {
          price_rule_id: { type: 'string', description: 'Price rule ID' },
          limit: { type: 'number', description: 'Results per page', default: 50, minimum: 1, maximum: 250 },
          page_info: { type: 'string', description: 'Cursor for pagination' },
        },
        required: ['price_rule_id'],
      },
      handler: async (input: unknown, client: ShopifyClient) => {
        const validated = ListDiscountCodesInput.parse(input);
        const { price_rule_id, ...params } = validated;
        const results = await client.list(`/price_rules/${price_rule_id}/discount_codes.json`, { params });
        return {
          content: [{ type: 'text' as const, text: JSON.stringify(results, null, 2) }],
        };
      },
    },
    {
      name: 'shopify_create_discount_code',
      description: 'Create a discount code for a price rule',
      inputSchema: {
        type: 'object' as const,
        properties: {
          price_rule_id: { type: 'string', description: 'Price rule ID' },
          code: { type: 'string', description: 'Discount code' },
          usage_count: { type: 'number', description: 'Number of times this code has been used' },
        },
        required: ['price_rule_id', 'code'],
      },
      handler: async (input: unknown, client: ShopifyClient) => {
        const validated = CreateDiscountCodeInput.parse(input);
        const { price_rule_id, ...codeData } = validated;
        const result = await client.create(`/price_rules/${price_rule_id}/discount_codes.json`, { discount_code: codeData });
        return {
          content: [{ type: 'text' as const, text: JSON.stringify(result, null, 2) }],
        };
      },
    },
  ];
