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

const ListWebhooksInput = z.object({
  limit: z.number().min(1).max(250).default(50).describe('Results per page'),
  page_info: z.string().optional().describe('Cursor for pagination'),
  topic: z.string().optional().describe('Filter by webhook topic'),
  address: z.string().optional().describe('Filter by webhook destination URL'),
});

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

const CreateWebhookInput = z.object({
  topic: z.string().describe('Webhook topic (e.g., "orders/create", "products/update", "customers/delete")'),
  address: z.string().describe('Webhook destination URL'),
  format: z.enum(['json', 'xml']).default('json').describe('Payload format'),
  fields: z.array(z.string()).optional().describe('List of fields to include in webhook payload'),
  metafield_namespaces: z.array(z.string()).optional().describe('Metafield namespaces to include'),
  private_metafield_namespaces: z.array(z.string()).optional().describe('Private metafield namespaces to include'),
});

const UpdateWebhookInput = z.object({
  id: z.string().describe('Webhook ID'),
  topic: z.string().optional().describe('Webhook topic'),
  address: z.string().optional().describe('Webhook destination URL'),
  format: z.enum(['json', 'xml']).optional().describe('Payload format'),
  fields: z.array(z.string()).optional().describe('List of fields to include in webhook payload'),
});

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

export default [
    {
      name: 'shopify_list_webhooks',
      description: 'List all webhook subscriptions with optional filtering by topic or address',
      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' },
          topic: { type: 'string', description: 'Filter by webhook topic' },
          address: { type: 'string', description: 'Filter by webhook destination URL' },
        },
      },
      handler: async (input: unknown, client: ShopifyClient) => {
        const validated = ListWebhooksInput.parse(input);
        const results = await client.list('/webhooks.json', { params: validated });
        return {
          content: [{ type: 'text' as const, text: JSON.stringify(results, null, 2) }],
        };
      },
    },
    {
      name: 'shopify_get_webhook',
      description: 'Get a specific webhook subscription by ID',
      inputSchema: {
        type: 'object' as const,
        properties: {
          id: { type: 'string', description: 'Webhook ID' },
        },
        required: ['id'],
      },
      handler: async (input: unknown, client: ShopifyClient) => {
        const validated = GetWebhookInput.parse(input);
        const result = await client.get(`/webhooks/${validated.id}.json`);
        return {
          content: [{ type: 'text' as const, text: JSON.stringify(result, null, 2) }],
        };
      },
    },
    {
      name: 'shopify_create_webhook',
      description: 'Create a new webhook subscription for a specific topic (e.g., orders/create, products/update)',
      inputSchema: {
        type: 'object' as const,
        properties: {
          topic: { type: 'string', description: 'Webhook topic (e.g., "orders/create", "products/update", "customers/delete")' },
          address: { type: 'string', description: 'Webhook destination URL' },
          format: { type: 'string', enum: ['json', 'xml'], description: 'Payload format', default: 'json' },
          fields: { type: 'array', description: 'List of fields to include in webhook payload', items: { type: 'string' } },
          metafield_namespaces: { type: 'array', description: 'Metafield namespaces to include', items: { type: 'string' } },
          private_metafield_namespaces: { type: 'array', description: 'Private metafield namespaces to include', items: { type: 'string' } },
        },
        required: ['topic', 'address'],
      },
      handler: async (input: unknown, client: ShopifyClient) => {
        const validated = CreateWebhookInput.parse(input);
        const result = await client.create('/webhooks.json', { webhook: validated });
        return {
          content: [{ type: 'text' as const, text: JSON.stringify(result, null, 2) }],
        };
      },
    },
    {
      name: 'shopify_update_webhook',
      description: 'Update an existing webhook subscription',
      inputSchema: {
        type: 'object' as const,
        properties: {
          id: { type: 'string', description: 'Webhook ID' },
          topic: { type: 'string', description: 'Webhook topic' },
          address: { type: 'string', description: 'Webhook destination URL' },
          format: { type: 'string', enum: ['json', 'xml'], description: 'Payload format' },
          fields: { type: 'array', description: 'List of fields to include in webhook payload', items: { type: 'string' } },
        },
        required: ['id'],
      },
      handler: async (input: unknown, client: ShopifyClient) => {
        const validated = UpdateWebhookInput.parse(input);
        const { id, ...updates } = validated;
        const result = await client.update(`/webhooks/${id}.json`, { webhook: updates });
        return {
          content: [{ type: 'text' as const, text: JSON.stringify(result, null, 2) }],
        };
      },
    },
    {
      name: 'shopify_delete_webhook',
      description: 'Delete a webhook subscription by ID',
      inputSchema: {
        type: 'object' as const,
        properties: {
          id: { type: 'string', description: 'Webhook ID' },
        },
        required: ['id'],
      },
      handler: async (input: unknown, client: ShopifyClient) => {
        const validated = DeleteWebhookInput.parse(input);
        await client.delete(`/webhooks/${validated.id}.json`);
        return {
          content: [{ type: 'text' as const, text: `Webhook ${validated.id} deleted successfully` }],
        };
      },
    },
  ];
