import { CloverClient } from '../clients/clover.js';
import { CloverCashEvent } from '../types/index.js';

export function createCashTools(client: CloverClient) {
  return {
    clover_list_cash_events: {
      description: 'List cash drawer events',
      inputSchema: {
        type: 'object',
        properties: {
          deviceId: {
            type: 'string',
            description: 'Filter by device ID',
          },
          employeeId: {
            type: 'string',
            description: 'Filter by employee ID',
          },
          filter: {
            type: 'string',
            description: 'Additional filter expression',
          },
          limit: {
            type: 'number',
            description: 'Maximum number of events to return',
          },
        },
      },
      handler: async (args: any) => {
        let filter = args.filter || '';
        if (args.deviceId) {
          filter += (filter ? ' AND ' : '') + `device.id='${args.deviceId}'`;
        }
        if (args.employeeId) {
          filter += (filter ? ' AND ' : '') + `employee.id='${args.employeeId}'`;
        }

        const events = await client.fetchPaginated<CloverCashEvent>(
          '/cash_events',
          { filter },
          args.limit
        );
        return { cashEvents: events, count: events.length };
      },
    },

    clover_get_cash_drawer: {
      description: 'Get current cash drawer status for a device',
      inputSchema: {
        type: 'object',
        properties: {
          deviceId: { type: 'string', description: 'Device ID' },
        },
        required: ['deviceId'],
      },
      handler: async (args: any) => {
        // Get all cash events for this device
        const events = await client.fetchPaginated<CloverCashEvent>(
          '/cash_events',
          { filter: `device.id='${args.deviceId}'` }
        );

        // Calculate current balance
        let balance = 0;
        events.forEach((event) => {
          balance += event.amountChange;
        });

        return {
          deviceId: args.deviceId,
          currentBalance: balance,
          eventCount: events.length,
          lastEvent: events[0] || null,
        };
      },
    },
  };
}
