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

const ListProductsInput = 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(['active', 'archived', 'draft']).optional().describe('Filter by status'),
  product_type: z.string().optional().describe('Filter by product type'),
  vendor: z.string().optional().describe('Filter by vendor'),
  collection_id: z.string().optional().describe('Filter by collection'),
  created_at_min: z.string().optional().describe('Filter by min creation date (ISO 8601)'),
  updated_at_min: z.string().optional().describe('Filter by min update date (ISO 8601)'),
});

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

const CreateProductInput = z.object({
  title: z.string().describe('Product title'),
  body_html: z.string().optional().describe('Product description HTML'),
  vendor: z.string().optional().describe('Product vendor'),
  product_type: z.string().optional().describe('Product type/category'),
  tags: z.string().optional().describe('Comma-separated tags'),
  status: z.enum(['active', 'archived', 'draft']).optional().describe('Product status'),
  variants: z.array(z.object({
    price: z.string().describe('Variant price'),
    sku: z.string().optional().describe('SKU'),
    inventory_quantity: z.number().optional().describe('Inventory quantity'),
    option1: z.string().optional().describe('Option 1 value'),
    option2: z.string().optional().describe('Option 2 value'),
    option3: z.string().optional().describe('Option 3 value'),
  })).optional().describe('Product variants'),
  images: z.array(z.object({
    src: z.string().describe('Image URL'),
    alt: z.string().optional().describe('Alt text'),
  })).optional().describe('Product images'),
});

const UpdateProductInput = z.object({
  id: z.string().describe('Product ID'),
  title: z.string().optional().describe('Product title'),
  body_html: z.string().optional().describe('Product description HTML'),
  vendor: z.string().optional().describe('Product vendor'),
  product_type: z.string().optional().describe('Product type/category'),
  tags: z.string().optional().describe('Comma-separated tags'),
  status: z.enum(['active', 'archived', 'draft']).optional().describe('Product status'),
});

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

const SearchProductsInput = z.object({
  query: z.string().describe('Search query (title, tag, sku, vendor, etc.)'),
  limit: z.number().min(1).max(250).default(50).describe('Results per page'),
  page_info: z.string().optional().describe('Cursor for pagination'),
});

export default [
  {
    name: 'shopify_list_products',
    description: 'List products with pagination, filtering by status, type, vendor, collection, 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: ['active', 'archived', 'draft'], description: 'Filter by status' },
        product_type: { type: 'string', description: 'Filter by product type' },
        vendor: { type: 'string', description: 'Filter by vendor' },
        collection_id: { type: 'string', description: 'Filter by collection' },
        created_at_min: { type: 'string', description: 'Filter by min creation date (ISO 8601)' },
        updated_at_min: { type: 'string', description: 'Filter by min update date (ISO 8601)' },
      },
    },
    handler: async (input: unknown, client: ShopifyClient) => {
      const validated = ListProductsInput.parse(input);
      const results = await client.list('/products.json', { params: validated });
      return {
        content: [{ type: 'text' as const, text: JSON.stringify(results, null, 2) }],
      };
    },
  },
  {
    name: 'shopify_get_product',
    description: 'Get a specific product by ID with optional field filtering',
    inputSchema: {
      type: 'object' as const,
      properties: {
        id: { type: 'string', description: 'Product ID' },
        fields: { type: 'string', description: 'Comma-separated list of fields to retrieve' },
      },
      required: ['id'],
    },
    handler: async (input: unknown, client: ShopifyClient) => {
      const validated = GetProductInput.parse(input);
      const result = await client.get(`/products/${validated.id}.json`, {
        params: validated.fields ? { fields: validated.fields } : {},
      });
      return {
        content: [{ type: 'text' as const, text: JSON.stringify(result, null, 2) }],
      };
    },
  },
  {
    name: 'shopify_create_product',
    description: 'Create a new product with variants and images',
    inputSchema: {
      type: 'object' as const,
      properties: {
        title: { type: 'string', description: 'Product title' },
        body_html: { type: 'string', description: 'Product description HTML' },
        vendor: { type: 'string', description: 'Product vendor' },
        product_type: { type: 'string', description: 'Product type/category' },
        tags: { type: 'string', description: 'Comma-separated tags' },
        status: { type: 'string', enum: ['active', 'archived', 'draft'], description: 'Product status' },
        variants: {
          type: 'array',
          description: 'Product variants',
          items: {
            type: 'object',
            properties: {
              price: { type: 'string', description: 'Variant price' },
              sku: { type: 'string', description: 'SKU' },
              inventory_quantity: { type: 'number', description: 'Inventory quantity' },
              option1: { type: 'string', description: 'Option 1 value' },
              option2: { type: 'string', description: 'Option 2 value' },
              option3: { type: 'string', description: 'Option 3 value' },
            },
          },
        },
        images: {
          type: 'array',
          description: 'Product images',
          items: {
            type: 'object',
            properties: {
              src: { type: 'string', description: 'Image URL' },
              alt: { type: 'string', description: 'Alt text' },
            },
          },
        },
      },
      required: ['title'],
    },
    handler: async (input: unknown, client: ShopifyClient) => {
      const validated = CreateProductInput.parse(input);
      const result = await client.create('/products.json', { product: validated });
      return {
        content: [{ type: 'text' as const, text: JSON.stringify(result, null, 2) }],
      };
    },
  },
  {
    name: 'shopify_update_product',
    description: 'Update an existing product',
    inputSchema: {
      type: 'object' as const,
      properties: {
        id: { type: 'string', description: 'Product ID' },
        title: { type: 'string', description: 'Product title' },
        body_html: { type: 'string', description: 'Product description HTML' },
        vendor: { type: 'string', description: 'Product vendor' },
        product_type: { type: 'string', description: 'Product type/category' },
        tags: { type: 'string', description: 'Comma-separated tags' },
        status: { type: 'string', enum: ['active', 'archived', 'draft'], description: 'Product status' },
      },
      required: ['id'],
    },
    handler: async (input: unknown, client: ShopifyClient) => {
      const validated = UpdateProductInput.parse(input);
      const { id, ...updates } = validated;
      const result = await client.update(`/products/${id}.json`, { product: updates });
      return {
        content: [{ type: 'text' as const, text: JSON.stringify(result, null, 2) }],
      };
    },
  },
  {
    name: 'shopify_delete_product',
    description: 'Delete a product by ID',
    inputSchema: {
      type: 'object' as const,
      properties: {
        id: { type: 'string', description: 'Product ID' },
      },
      required: ['id'],
    },
    handler: async (input: unknown, client: ShopifyClient) => {
      const validated = DeleteProductInput.parse(input);
      await client.delete(`/products/${validated.id}.json`);
      return {
        content: [{ type: 'text' as const, text: `Product ${validated.id} deleted successfully` }],
      };
    },
  },
  {
    name: 'shopify_search_products',
    description: 'Search products by query (searches title, tags, SKU, vendor, etc.)',
    inputSchema: {
      type: 'object' as const,
      properties: {
        query: { type: 'string', description: 'Search query (title, tag, sku, vendor, etc.)' },
        limit: { type: 'number', description: 'Results per page', default: 50, minimum: 1, maximum: 250 },
        page_info: { type: 'string', description: 'Cursor for pagination' },
      },
      required: ['query'],
    },
    handler: async (input: unknown, client: ShopifyClient) => {
      const validated = SearchProductsInput.parse(input);
      const results = await client.list('/products.json', {
        params: { ...validated, title: validated.query },
      });
      return {
        content: [{ type: 'text' as const, text: JSON.stringify(results, null, 2) }],
      };
    },
  },
];
