/**
 * Table & Floor Management Tools
 */

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

export const tableTools = {
  touchbistro_list_tables: {
    description: 'List all tables with current status, assigned servers, and guest counts.',
    parameters: z.object({
      status: z
        .enum(['available', 'occupied', 'reserved', 'cleaning', 'out_of_service'])
        .optional()
        .describe('Filter by table status'),
      sectionId: z.string().optional().describe('Filter by section ID'),
    }),
    handler: async (params: any, client: TouchBistroApiClient) => {
      const filter: any = {};
      if (params.status) filter.status = params.status;
      if (params.sectionId) filter.sectionId = params.sectionId;

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

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

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

  touchbistro_get_table: {
    description: 'Get detailed information about a specific table.',
    parameters: z.object({
      tableId: z.string().describe('Table ID'),
    }),
    handler: async (params: any, client: TouchBistroApiClient) => {
      const response = await client.getTable(params.tableId);

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

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

  touchbistro_create_table: {
    description: 'Create a new table in a section with position and capacity.',
    parameters: z.object({
      number: z.string().describe('Table number'),
      name: z.string().optional().describe('Table name'),
      sectionId: z.string().describe('Section ID'),
      capacity: z.number().describe('Maximum guest capacity'),
      shape: z.enum(['square', 'rectangle', 'circle', 'oval']).describe('Table shape'),
      positionX: z.number().describe('X position on floor plan'),
      positionY: z.number().describe('Y position on floor plan'),
      rotation: z.number().optional().describe('Rotation in degrees'),
    }),
    handler: async (params: any, client: TouchBistroApiClient) => {
      const response = await client.createTable(params);

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

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

  touchbistro_update_table: {
    description: 'Update table details like capacity, position, or name.',
    parameters: z.object({
      tableId: z.string().describe('Table ID'),
      number: z.string().optional().describe('Table number'),
      name: z.string().optional().describe('Table name'),
      capacity: z.number().optional().describe('Maximum guest capacity'),
      positionX: z.number().optional().describe('X position on floor plan'),
      positionY: z.number().optional().describe('Y position on floor plan'),
      rotation: z.number().optional().describe('Rotation in degrees'),
    }),
    handler: async (params: any, client: TouchBistroApiClient) => {
      const { tableId, ...updates } = params;
      const response = await client.updateTable(tableId, updates);

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

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

  touchbistro_update_table_status: {
    description: 'Update table status (seat guests, mark as cleaning, reserve, etc.).',
    parameters: z.object({
      tableId: z.string().describe('Table ID'),
      status: z
        .enum(['available', 'occupied', 'reserved', 'cleaning', 'out_of_service'])
        .describe('New table status'),
      guestCount: z.number().optional().describe('Number of guests (for occupied status)'),
    }),
    handler: async (params: any, client: TouchBistroApiClient) => {
      const response = await client.updateTableStatus(params.tableId, params.status, params.guestCount);

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

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

  touchbistro_assign_server_to_table: {
    description: 'Assign a server to a table.',
    parameters: z.object({
      tableId: z.string().describe('Table ID'),
      serverId: z.string().describe('Server/staff ID'),
    }),
    handler: async (params: any, client: TouchBistroApiClient) => {
      const response = await client.assignServer(params.tableId, params.serverId);

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

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

  touchbistro_list_sections: {
    description: 'List all sections/stations with assigned servers and table counts.',
    parameters: z.object({}),
    handler: async (params: any, client: TouchBistroApiClient) => {
      const response = await client.getSections();

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

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

  touchbistro_create_section: {
    description: 'Create a new section/station on a floor plan.',
    parameters: z.object({
      name: z.string().describe('Section name'),
      floorPlanId: z.string().describe('Floor plan ID'),
      color: z.string().optional().describe('Color code for display'),
      assignedServerIds: z.array(z.string()).optional().describe('Assigned server IDs'),
    }),
    handler: async (params: any, client: TouchBistroApiClient) => {
      const response = await client.createSection(params);

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

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

  touchbistro_list_floor_plans: {
    description: 'List all floor plans with sections and table layouts.',
    parameters: z.object({}),
    handler: async (params: any, client: TouchBistroApiClient) => {
      const response = await client.getFloorPlans();

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

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

  touchbistro_get_active_floor_plan: {
    description: 'Get the currently active floor plan with all tables and sections.',
    parameters: z.object({}),
    handler: async (params: any, client: TouchBistroApiClient) => {
      const response = await client.getActiveFloorPlan();

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

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