/**
 * Menu Management Tools
 */

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

export const menuTools = {
  touchbistro_list_menu_items: {
    description:
      'List all menu items with optional filters (category, availability, search). Returns prices, descriptions, and modifiers.',
    parameters: z.object({
      categoryId: z.string().optional().describe('Filter by category ID'),
      available: z.boolean().optional().describe('Filter by availability'),
      search: z.string().optional().describe('Search by name or description'),
    }),
    handler: async (params: any, client: TouchBistroApiClient) => {
      const filter: any = {};
      if (params.categoryId) filter.categoryId = params.categoryId;
      if (params.available !== undefined) filter.available = params.available;
      if (params.search) filter.search = params.search;

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

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

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

  touchbistro_get_menu_item: {
    description: 'Get detailed information about a specific menu item including pricing, modifiers, and nutrition.',
    parameters: z.object({
      itemId: z.string().describe('Menu item ID'),
    }),
    handler: async (params: any, client: TouchBistroApiClient) => {
      const response = await client.getMenuItem(params.itemId);

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

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

  touchbistro_create_menu_item: {
    description: 'Create a new menu item with pricing, category, and modifiers.',
    parameters: z.object({
      name: z.string().describe('Item name'),
      description: z.string().optional().describe('Item description'),
      price: z.number().describe('Item price'),
      cost: z.number().optional().describe('Item cost'),
      categoryId: z.string().describe('Category ID'),
      sku: z.string().optional().describe('SKU'),
      barcode: z.string().optional().describe('Barcode'),
      taxable: z.boolean().default(true).describe('Is taxable'),
      available: z.boolean().default(true).describe('Is available'),
      prepTime: z.number().optional().describe('Preparation time in minutes'),
      modifierGroupIds: z.array(z.string()).optional().describe('Modifier group IDs'),
      allergens: z.array(z.string()).optional().describe('Allergen information'),
      image: z.string().optional().describe('Image URL'),
    }),
    handler: async (params: any, client: TouchBistroApiClient) => {
      const response = await client.createMenuItem(params);

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

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

  touchbistro_update_menu_item: {
    description: 'Update menu item details including price, availability, and description.',
    parameters: z.object({
      itemId: z.string().describe('Menu item ID'),
      name: z.string().optional().describe('Updated name'),
      description: z.string().optional().describe('Updated description'),
      price: z.number().optional().describe('Updated price'),
      cost: z.number().optional().describe('Updated cost'),
      available: z.boolean().optional().describe('Availability'),
      prepTime: z.number().optional().describe('Preparation time in minutes'),
      image: z.string().optional().describe('Image URL'),
    }),
    handler: async (params: any, client: TouchBistroApiClient) => {
      const { itemId, ...updates } = params;
      const response = await client.updateMenuItem(itemId, updates);

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

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

  touchbistro_delete_menu_item: {
    description: 'Delete a menu item permanently.',
    parameters: z.object({
      itemId: z.string().describe('Menu item ID to delete'),
    }),
    handler: async (params: any, client: TouchBistroApiClient) => {
      const response = await client.deleteMenuItem(params.itemId);

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

      return {
        content: [
          {
            type: 'text',
            text: 'Menu item deleted successfully!',
          },
        ],
      };
    },
  },

  touchbistro_list_menu_categories: {
    description: 'List all menu categories with item counts and hierarchy.',
    parameters: z.object({}),
    handler: async (params: any, client: TouchBistroApiClient) => {
      const response = await client.getMenuCategories();

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

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

  touchbistro_create_menu_category: {
    description: 'Create a new menu category with name and display order.',
    parameters: z.object({
      name: z.string().describe('Category name'),
      description: z.string().optional().describe('Category description'),
      parentCategoryId: z.string().optional().describe('Parent category ID (for sub-categories)'),
      sortOrder: z.number().optional().describe('Display sort order'),
      available: z.boolean().default(true).describe('Is available'),
    }),
    handler: async (params: any, client: TouchBistroApiClient) => {
      const response = await client.createMenuCategory(params);

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

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

  touchbistro_update_menu_category: {
    description: 'Update menu category details.',
    parameters: z.object({
      categoryId: z.string().describe('Category ID'),
      name: z.string().optional().describe('Updated name'),
      description: z.string().optional().describe('Updated description'),
      sortOrder: z.number().optional().describe('Display sort order'),
      available: z.boolean().optional().describe('Availability'),
    }),
    handler: async (params: any, client: TouchBistroApiClient) => {
      const { categoryId, ...updates } = params;
      const response = await client.updateMenuCategory(categoryId, updates);

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

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

  touchbistro_delete_menu_category: {
    description: 'Delete a menu category (items in category must be reassigned first).',
    parameters: z.object({
      categoryId: z.string().describe('Category ID to delete'),
    }),
    handler: async (params: any, client: TouchBistroApiClient) => {
      const response = await client.deleteMenuCategory(params.categoryId);

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

      return {
        content: [
          {
            type: 'text',
            text: 'Menu category deleted successfully!',
          },
        ],
      };
    },
  },

  touchbistro_list_menus: {
    description: 'List all menus (breakfast, lunch, dinner, etc.) with active times and categories.',
    parameters: z.object({}),
    handler: async (params: any, client: TouchBistroApiClient) => {
      const response = await client.getMenus();

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

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

  touchbistro_create_menu: {
    description: 'Create a new menu with time-based availability (breakfast, lunch, happy hour, etc.).',
    parameters: z.object({
      name: z.string().describe('Menu name'),
      description: z.string().optional().describe('Menu description'),
      startTime: z.string().optional().describe('Start time (HH:mm format)'),
      endTime: z.string().optional().describe('End time (HH:mm format)'),
      daysOfWeek: z.array(z.number()).optional().describe('Active days (0=Sunday, 6=Saturday)'),
      available: z.boolean().default(true).describe('Is available'),
    }),
    handler: async (params: any, client: TouchBistroApiClient) => {
      const response = await client.createMenu(params);

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

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

  touchbistro_update_menu: {
    description: 'Update menu details and availability schedule.',
    parameters: z.object({
      menuId: z.string().describe('Menu ID'),
      name: z.string().optional().describe('Updated name'),
      description: z.string().optional().describe('Updated description'),
      startTime: z.string().optional().describe('Start time (HH:mm format)'),
      endTime: z.string().optional().describe('End time (HH:mm format)'),
      daysOfWeek: z.array(z.number()).optional().describe('Active days (0=Sunday, 6=Saturday)'),
      available: z.boolean().optional().describe('Availability'),
    }),
    handler: async (params: any, client: TouchBistroApiClient) => {
      const { menuId, ...updates } = params;
      const response = await client.updateMenu(menuId, updates);

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

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

  touchbistro_list_modifier_groups: {
    description: 'List all modifier groups (toppings, sides, cooking temps, etc.).',
    parameters: z.object({}),
    handler: async (params: any, client: TouchBistroApiClient) => {
      const response = await client.getModifierGroups();

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

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

  touchbistro_create_modifier_group: {
    description: 'Create a new modifier group with modifiers.',
    parameters: z.object({
      name: z.string().describe('Modifier group name'),
      minSelections: z.number().default(0).describe('Minimum selections required'),
      maxSelections: z.number().default(1).describe('Maximum selections allowed'),
      required: z.boolean().default(false).describe('Is required'),
      modifiers: z
        .array(
          z.object({
            name: z.string(),
            price: z.number(),
            available: z.boolean().default(true),
            sortOrder: z.number().optional(),
          })
        )
        .describe('Modifiers in this group'),
    }),
    handler: async (params: any, client: TouchBistroApiClient) => {
      const response = await client.createModifierGroup(params);

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

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