/**
 * Xero Report Tools
 * Handles financial reports: P&L, balance sheet, trial balance, bank summary, aged receivables/payables
 */

import { z } from 'zod';
import { XeroClient } from '../clients/xero.js';
import type { Tool } from '@modelcontextprotocol/sdk/types.js';

export function getTools(_client: XeroClient): Tool[] {
  return [
    // Profit & Loss
    {
      name: 'xero_get_profit_and_loss',
      description: 'Get Profit & Loss report (income statement). Shows revenue and expenses over a period.',
      inputSchema: {
        type: 'object',
        properties: {
          fromDate: { 
            type: 'string', 
            description: 'Start date (YYYY-MM-DD)' 
          },
          toDate: { 
            type: 'string', 
            description: 'End date (YYYY-MM-DD)' 
          },
          periods: {
            type: 'number',
            description: 'Number of periods to compare (e.g., 2 for current vs previous)'
          },
          timeframe: {
            type: 'string',
            enum: ['MONTH', 'QUARTER', 'YEAR'],
            description: 'Timeframe for period comparison'
          },
          trackingCategoryID: {
            type: 'string',
            description: 'Filter by tracking category ID'
          },
          trackingOptionID: {
            type: 'string',
            description: 'Filter by tracking option ID'
          },
          standardLayout: {
            type: 'boolean',
            description: 'Use standard layout (true) or cash layout (false)'
          }
        }
      }
    },

    // Balance Sheet
    {
      name: 'xero_get_balance_sheet',
      description: 'Get Balance Sheet report. Shows assets, liabilities, and equity at a point in time.',
      inputSchema: {
        type: 'object',
        properties: {
          date: {
            type: 'string',
            description: 'Report date (YYYY-MM-DD). Defaults to today.'
          },
          periods: {
            type: 'number',
            description: 'Number of periods to compare (e.g., 12 for monthly comparison)'
          },
          timeframe: {
            type: 'string',
            enum: ['MONTH', 'QUARTER', 'YEAR'],
            description: 'Timeframe for period comparison'
          },
          trackingCategoryID: {
            type: 'string',
            description: 'Filter by tracking category ID'
          },
          standardLayout: {
            type: 'boolean',
            description: 'Use standard layout'
          }
        }
      }
    },

    // Trial Balance
    {
      name: 'xero_get_trial_balance',
      description: 'Get Trial Balance report. Shows all account balances at a point in time.',
      inputSchema: {
        type: 'object',
        properties: {
          date: {
            type: 'string',
            description: 'Report date (YYYY-MM-DD). Defaults to today.'
          }
        }
      }
    },

    // Bank Summary
    {
      name: 'xero_get_bank_summary',
      description: 'Get Bank Summary report. Shows bank account activity and balances.',
      inputSchema: {
        type: 'object',
        properties: {
          fromDate: {
            type: 'string',
            description: 'Start date (YYYY-MM-DD)'
          },
          toDate: {
            type: 'string',
            description: 'End date (YYYY-MM-DD)'
          }
        }
      }
    },

    // Aged Receivables (AR aging)
    {
      name: 'xero_get_aged_receivables',
      description: 'Get Aged Receivables report. Shows outstanding customer invoices grouped by age (current, 30, 60, 90+ days).',
      inputSchema: {
        type: 'object',
        properties: {
          date: {
            type: 'string',
            description: 'Report date (YYYY-MM-DD). Defaults to today.'
          },
          fromDate: {
            type: 'string',
            description: 'Filter from date (YYYY-MM-DD)'
          },
          toDate: {
            type: 'string',
            description: 'Filter to date (YYYY-MM-DD)'
          },
          contactID: {
            type: 'string',
            description: 'Filter by specific contact/customer ID'
          }
        }
      }
    },

    // Aged Payables (AP aging)
    {
      name: 'xero_get_aged_payables',
      description: 'Get Aged Payables report. Shows outstanding supplier bills grouped by age (current, 30, 60, 90+ days).',
      inputSchema: {
        type: 'object',
        properties: {
          date: {
            type: 'string',
            description: 'Report date (YYYY-MM-DD). Defaults to today.'
          },
          fromDate: {
            type: 'string',
            description: 'Filter from date (YYYY-MM-DD)'
          },
          toDate: {
            type: 'string',
            description: 'Filter to date (YYYY-MM-DD)'
          },
          contactID: {
            type: 'string',
            description: 'Filter by specific contact/supplier ID'
          }
        }
      }
    },

    // Executive Summary
    {
      name: 'xero_get_executive_summary',
      description: 'Get Executive Summary report. High-level overview of cash position, receivables, payables, and expenses.',
      inputSchema: {
        type: 'object',
        properties: {
          date: {
            type: 'string',
            description: 'Report date (YYYY-MM-DD). Defaults to today.'
          }
        }
      }
    },

    // Budget Summary
    {
      name: 'xero_get_budget_summary',
      description: 'Get Budget Summary report. Compares actual vs budget performance.',
      inputSchema: {
        type: 'object',
        properties: {
          date: {
            type: 'string',
            description: 'Report date (YYYY-MM-DD)'
          },
          periods: {
            type: 'number',
            description: 'Number of periods'
          },
          timeframe: {
            type: 'string',
            enum: ['MONTH', 'QUARTER', 'YEAR'],
            description: 'Timeframe'
          }
        }
      }
    }
  ];
}

export async function handleReportTool(
  toolName: string,
  args: Record<string, unknown>,
  client: XeroClient
): Promise<unknown> {
  switch (toolName) {
    case 'xero_get_profit_and_loss': {
      const schema = z.object({
        fromDate: z.string().optional(),
        toDate: z.string().optional(),
        periods: z.number().optional(),
        timeframe: z.enum(['MONTH', 'QUARTER', 'YEAR']).optional(),
        trackingCategoryID: z.string().optional(),
        trackingOptionID: z.string().optional(),
        standardLayout: z.boolean().optional()
      });
      const data = schema.parse(args);
      
      return await client.getProfitAndLoss(data.fromDate, data.toDate);
    }

    case 'xero_get_balance_sheet': {
      const schema = z.object({
        date: z.string().optional(),
        periods: z.number().optional(),
        timeframe: z.enum(['MONTH', 'QUARTER', 'YEAR']).optional(),
        trackingCategoryID: z.string().optional(),
        standardLayout: z.boolean().optional()
      });
      const data = schema.parse(args);
      
      return await client.getBalanceSheet(data.date, data.periods);
    }

    case 'xero_get_trial_balance': {
      const schema = z.object({
        date: z.string().optional()
      });
      const data = schema.parse(args);
      
      return await client.getTrialBalance(data.date);
    }

    case 'xero_get_bank_summary': {
      const schema = z.object({
        fromDate: z.string().optional(),
        toDate: z.string().optional()
      });
      const data = schema.parse(args);
      
      return await client.getBankSummary(data.fromDate, data.toDate);
    }

    case 'xero_get_aged_receivables': {
      const schema = z.object({
        date: z.string().optional(),
        fromDate: z.string().optional(),
        toDate: z.string().optional(),
        contactID: z.string().optional()
      });
      const data = schema.parse(args);
      
      // Build query params
      let url = '/Reports/AgedReceivablesByContact';
      const params: string[] = [];
      if (data.date) params.push(`date=${data.date}`);
      if (data.fromDate) params.push(`fromDate=${data.fromDate}`);
      if (data.toDate) params.push(`toDate=${data.toDate}`);
      if (data.contactID) params.push(`contactID=${data.contactID}`);
      
      if (params.length > 0) {
        url += '?' + params.join('&');
      }
      
      return await client.getReport(url);
    }

    case 'xero_get_aged_payables': {
      const schema = z.object({
        date: z.string().optional(),
        fromDate: z.string().optional(),
        toDate: z.string().optional(),
        contactID: z.string().optional()
      });
      const data = schema.parse(args);
      
      let url = '/Reports/AgedPayablesByContact';
      const params: string[] = [];
      if (data.date) params.push(`date=${data.date}`);
      if (data.fromDate) params.push(`fromDate=${data.fromDate}`);
      if (data.toDate) params.push(`toDate=${data.toDate}`);
      if (data.contactID) params.push(`contactID=${data.contactID}`);
      
      if (params.length > 0) {
        url += '?' + params.join('&');
      }
      
      return await client.getReport(url);
    }

    case 'xero_get_executive_summary': {
      const schema = z.object({
        date: z.string().optional()
      });
      const data = schema.parse(args);
      
      return await client.getExecutiveSummary(data.date);
    }

    case 'xero_get_budget_summary': {
      const schema = z.object({
        date: z.string().optional(),
        periods: z.number().optional(),
        timeframe: z.enum(['MONTH', 'QUARTER', 'YEAR']).optional()
      });
      const data = schema.parse(args);
      
      let url = '/Reports/BudgetSummary';
      const params: string[] = [];
      if (data.date) params.push(`date=${data.date}`);
      if (data.periods) params.push(`periods=${data.periods}`);
      if (data.timeframe) params.push(`timeframe=${data.timeframe}`);
      
      if (params.length > 0) {
        url += '?' + params.join('&');
      }
      
      return await client.getReport(url);
    }

    default:
      throw new Error(`Unknown report tool: ${toolName}`);
  }
}
