/**
 * Inventory Management Tools
 */

import { z } from 'zod';
import type { TouchBistroApiClient } from '../lib/api-client.js';

export const inventoryTools = {
  touchbistro_list_inventory_items: {
    description: 'List all inventory items with stock levels, costs, and suppliers.',
    parameters: z.object({
      category: z.string().optional().describe('Filter by category'),
      lowStock: z.boolean().optional().describe('Show only low stock items'),
    }),
    handler: async (params: any, client: TouchBistroApiClient) => {
      if (params.lowStock) {
        const response = await client.getLowStockItems();
        if (!response.success) {
          throw new Error(response.error?.message || 'Failed to fetch low stock items');
        }
        return {
          content: [{ type: 'text', text: JSON.stringify(response.data, null, 2) }],
        };
      }

      const filter: any = {};
      if (params.category) filter.category = params.category;

      const response = await client.getInventoryItems({ filter });

      if (!response.success) {
        throw new Error(response.error?.message || 'Failed to fetch inventory items');
      }

      return {
        content: [
          {
            type: 'text',
            text: JSON.stringify(response.data, null, 2),
          },
        ],
      };
    },
  },

  touchbistro_get_inventory_item: {
    description: 'Get detailed information about a specific inventory item.',
    parameters: z.object({
      itemId: z.string().describe('Inventory item ID'),
    }),
    handler: async (params: any, client: TouchBistroApiClient) => {
      const response = await client.getInventoryItem(params.itemId);

      if (!response.success) {
        throw new Error(response.error?.message || 'Failed to fetch inventory item');
      }

      return {
        content: [
          {
            type: 'text',
            text: JSON.stringify(response.data, null, 2),
          },
        ],
      };
    },
  },

  touchbistro_create_inventory_item: {
    description: 'Create a new inventory item with stock tracking.',
    parameters: z.object({
      name: z.string().describe('Item name'),
      category: z.string().describe('Item category'),
      unit: z.string().describe('Unit of measurement (e.g., lb, oz, each)'),
      currentStock: z.number().describe('Current stock quantity'),
      parLevel: z.number().describe('Par level (target stock)'),
      reorderPoint: z.number().describe('Reorder point (minimum before restocking)'),
      reorderQuantity: z.number().describe('Default reorder quantity'),
      unitCost: z.number().describe('Cost per unit'),
      supplierId: z.string().optional().describe('Supplier ID'),
      sku: z.string().optional().describe('SKU'),
      barcode: z.string().optional().describe('Barcode'),
      location: z.string().optional().describe('Storage location'),
    }),
    handler: async (params: any, client: TouchBistroApiClient) => {
      const response = await client.createInventoryItem(params);

      if (!response.success) {
        throw new Error(response.error?.message || 'Failed to create inventory item');
      }

      return {
        content: [
          {
            type: 'text',
            text: `Inventory item created!\n\n${JSON.stringify(response.data, null, 2)}`,
          },
        ],
      };
    },
  },

  touchbistro_update_inventory_item: {
    description: 'Update inventory item details.',
    parameters: z.object({
      itemId: z.string().describe('Inventory item ID'),
      name: z.string().optional().describe('Item name'),
      category: z.string().optional().describe('Item category'),
      parLevel: z.number().optional().describe('Par level'),
      reorderPoint: z.number().optional().describe('Reorder point'),
      reorderQuantity: z.number().optional().describe('Reorder quantity'),
      unitCost: z.number().optional().describe('Cost per unit'),
      supplierId: z.string().optional().describe('Supplier ID'),
      location: z.string().optional().describe('Storage location'),
    }),
    handler: async (params: any, client: TouchBistroApiClient) => {
      const { itemId, ...updates } = params;
      const response = await client.updateInventoryItem(itemId, updates);

      if (!response.success) {
        throw new Error(response.error?.message || 'Failed to update inventory item');
      }

      return {
        content: [
          {
            type: 'text',
            text: `Inventory item updated!\n\n${JSON.stringify(response.data, null, 2)}`,
          },
        ],
      };
    },
  },

  touchbistro_adjust_stock: {
    description: 'Adjust inventory stock levels (add, subtract, or correct).',
    parameters: z.object({
      itemId: z.string().describe('Inventory item ID'),
      quantity: z.number().describe('Quantity to adjust (positive or negative)'),
      type: z.enum(['addition', 'subtraction', 'correction']).describe('Adjustment type'),
      reason: z.string().describe('Reason for adjustment'),
    }),
    handler: async (params: any, client: TouchBistroApiClient) => {
      const response = await client.adjustStock(params.itemId, params.quantity, params.type, params.reason);

      if (!response.success) {
        throw new Error(response.error?.message || 'Failed to adjust stock');
      }

      return {
        content: [
          {
            type: 'text',
            text: `Stock adjusted!\n\n${JSON.stringify(response.data, null, 2)}`,
          },
        ],
      };
    },
  },

  touchbistro_list_suppliers: {
    description: 'List all suppliers with contact information.',
    parameters: z.object({}),
    handler: async (params: any, client: TouchBistroApiClient) => {
      const response = await client.getSuppliers();

      if (!response.success) {
        throw new Error(response.error?.message || 'Failed to fetch suppliers');
      }

      return {
        content: [
          {
            type: 'text',
            text: JSON.stringify(response.data, null, 2),
          },
        ],
      };
    },
  },

  touchbistro_create_supplier: {
    description: 'Create a new supplier.',
    parameters: z.object({
      name: z.string().describe('Supplier name'),
      contactName: z.string().optional().describe('Contact person name'),
      email: z.string().optional().describe('Email address'),
      phone: z.string().optional().describe('Phone number'),
      address: z.string().optional().describe('Address'),
      paymentTerms: z.string().optional().describe('Payment terms'),
      notes: z.string().optional().describe('Notes'),
    }),
    handler: async (params: any, client: TouchBistroApiClient) => {
      const response = await client.createSupplier(params);

      if (!response.success) {
        throw new Error(response.error?.message || 'Failed to create supplier');
      }

      return {
        content: [
          {
            type: 'text',
            text: `Supplier created!\n\n${JSON.stringify(response.data, null, 2)}`,
          },
        ],
      };
    },
  },

  touchbistro_list_purchase_orders: {
    description: 'List purchase orders with filters for status.',
    parameters: z.object({
      status: z.enum(['draft', 'sent', 'received', 'cancelled']).optional().describe('Filter by status'),
    }),
    handler: async (params: any, client: TouchBistroApiClient) => {
      const response = await client.getPurchaseOrders(params);

      if (!response.success) {
        throw new Error(response.error?.message || 'Failed to fetch purchase orders');
      }

      return {
        content: [
          {
            type: 'text',
            text: JSON.stringify(response.data, null, 2),
          },
        ],
      };
    },
  },

  touchbistro_create_purchase_order: {
    description: 'Create a new purchase order for a supplier.',
    parameters: z.object({
      supplierId: z.string().describe('Supplier ID'),
      items: z
        .array(
          z.object({
            inventoryItemId: z.string(),
            quantity: z.number(),
            unitCost: z.number(),
          })
        )
        .describe('Items to order'),
      expectedDate: z.string().optional().describe('Expected delivery date (ISO format)'),
      notes: z.string().optional().describe('Order notes'),
    }),
    handler: async (params: any, client: TouchBistroApiClient) => {
      const response = await client.createPurchaseOrder(params);

      if (!response.success) {
        throw new Error(response.error?.message || 'Failed to create purchase order');
      }

      return {
        content: [
          {
            type: 'text',
            text: `Purchase order created!\n\n${JSON.stringify(response.data, null, 2)}`,
          },
        ],
      };
    },
  },

  touchbistro_receive_purchase_order: {
    description: 'Mark a purchase order as received and update inventory.',
    parameters: z.object({
      orderId: z.string().describe('Purchase order ID'),
    }),
    handler: async (params: any, client: TouchBistroApiClient) => {
      const response = await client.receivePurchaseOrder(params.orderId);

      if (!response.success) {
        throw new Error(response.error?.message || 'Failed to receive purchase order');
      }

      return {
        content: [
          {
            type: 'text',
            text: `Purchase order received!\n\n${JSON.stringify(response.data, null, 2)}`,
          },
        ],
      };
    },
  },
};
