/**
 * Xero Tax Rate Tools
 * Handles tax rates (GST, VAT, sales tax, etc.)
 */

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

const TaxComponentSchema = z.object({
  Name: z.string(),
  Rate: z.number(),
  IsCompound: z.boolean().optional(),
  IsNonRecoverable: z.boolean().optional()
});

export function getTools(_client: XeroClient): Tool[] {
  return [
    // List tax rates
    {
      name: 'xero_list_tax_rates',
      description: 'List all tax rates. Tax rates define GST/VAT/sales tax calculations.',
      inputSchema: {
        type: 'object',
        properties: {
          where: { type: 'string', description: 'Filter expression (e.g., Status=="ACTIVE")' },
          order: { type: 'string', description: 'Order by field (e.g., Name ASC)' }
        }
      }
    },

    // Get single tax rate
    {
      name: 'xero_get_tax_rate',
      description: 'Get a specific tax rate by name or type. Tax rates are identified by TaxType (e.g., OUTPUT, INPUT, NONE).',
      inputSchema: {
        type: 'object',
        properties: {
          taxType: {
            type: 'string',
            description: 'Tax type (e.g., OUTPUT, INPUT, NONE, EXEMPTOUTPUT, etc.)'
          },
          name: {
            type: 'string',
            description: 'Tax rate name (e.g., "20% (VAT on Income)")'
          }
        }
      }
    },

    // Create tax rate
    {
      name: 'xero_create_tax_rate',
      description: 'Create a new tax rate. Used for custom tax configurations.',
      inputSchema: {
        type: 'object',
        properties: {
          name: { type: 'string', description: 'Tax rate name (e.g., "Custom GST 15%")' },
          taxType: {
            type: 'string',
            enum: [
              'INPUT', 'OUTPUT', 'CAPEXINPUT', 'CAPEXOUTPUT',
              'EXEMPTEXPENSES', 'EXEMPTINCOME', 'EXEMPTCAPITAL', 'EXEMPTOUTPUT',
              'INPUTTAXED', 'BASEXCLUDED', 'GSTONCAPIMPORTS', 'GSTONIMPORTS',
              'NONE', 'INPUT2', 'ECZROUTPUT', 'ZERORATEDINPUT', 'ZERORATEDOUTPUT',
              'REVERSECHARGES', 'RRINPUT', 'RROUTPUT'
            ],
            description: 'Tax type classification'
          },
          reportTaxType: {
            type: 'string',
            description: 'Report tax type for reporting purposes'
          },
          canApplyToAssets: { type: 'boolean', description: 'Can apply to assets' },
          canApplyToEquity: { type: 'boolean', description: 'Can apply to equity' },
          canApplyToExpenses: { type: 'boolean', description: 'Can apply to expenses' },
          canApplyToLiabilities: { type: 'boolean', description: 'Can apply to liabilities' },
          canApplyToRevenue: { type: 'boolean', description: 'Can apply to revenue' },
          displayTaxRate: { type: 'number', description: 'Display tax rate percentage (e.g., 15 for 15%)' },
          effectiveRate: { type: 'number', description: 'Effective tax rate percentage' },
          taxComponents: {
            type: 'array',
            items: {
              type: 'object',
              properties: {
                Name: { type: 'string', description: 'Component name' },
                Rate: { type: 'number', description: 'Component rate percentage' },
                IsCompound: { type: 'boolean', description: 'Is compound tax' },
                IsNonRecoverable: { type: 'boolean', description: 'Is non-recoverable' }
              },
              required: ['Name', 'Rate']
            },
            description: 'Tax components (for complex tax calculations)'
          }
        },
        required: ['name', 'taxType']
      }
    },

    // Update tax rate
    {
      name: 'xero_update_tax_rate',
      description: 'Update an existing tax rate. Can update name, status, and tax components.',
      inputSchema: {
        type: 'object',
        properties: {
          taxType: { type: 'string', description: 'Tax type to update' },
          name: { type: 'string', description: 'New name' },
          status: {
            type: 'string',
            enum: ['ACTIVE', 'DELETED', 'ARCHIVED'],
            description: 'New status'
          },
          taxComponents: {
            type: 'array',
            items: {
              type: 'object',
              properties: {
                Name: { type: 'string' },
                Rate: { type: 'number' },
                IsCompound: { type: 'boolean' }
              }
            }
          }
        },
        required: ['taxType']
      }
    }
  ];
}

export async function handleTaxRateTool(
  toolName: string,
  args: Record<string, unknown>,
  client: XeroClient
): Promise<unknown> {
  switch (toolName) {
    case 'xero_list_tax_rates': {
      const options = {
        where: args.where as string | undefined,
        order: args.order as string | undefined
      };
      return await client.getTaxRates(options);
    }

    case 'xero_get_tax_rate': {
      const schema = z.object({
        taxType: z.string().optional(),
        name: z.string().optional()
      });
      const data = schema.parse(args);
      
      // Build where clause
      let where = '';
      if (data.taxType) {
        where = `TaxType=="${data.taxType}"`;
      } else if (data.name) {
        where = `Name=="${data.name}"`;
      }
      
      const taxRates = await client.getTaxRates({ where });
      return taxRates.length > 0 ? taxRates[0] : null;
    }

    case 'xero_create_tax_rate': {
      const schema = z.object({
        name: z.string(),
        taxType: z.string(),
        reportTaxType: z.string().optional(),
        canApplyToAssets: z.boolean().optional(),
        canApplyToEquity: z.boolean().optional(),
        canApplyToExpenses: z.boolean().optional(),
        canApplyToLiabilities: z.boolean().optional(),
        canApplyToRevenue: z.boolean().optional(),
        displayTaxRate: z.number().optional(),
        effectiveRate: z.number().optional(),
        taxComponents: z.array(TaxComponentSchema).optional()
      });
      const data = schema.parse(args);
      
      const taxRate: any = {
        Name: data.name,
        TaxType: data.taxType
      };
      
      if (data.reportTaxType) taxRate.ReportTaxType = data.reportTaxType;
      if (data.canApplyToAssets !== undefined) taxRate.CanApplyToAssets = data.canApplyToAssets;
      if (data.canApplyToEquity !== undefined) taxRate.CanApplyToEquity = data.canApplyToEquity;
      if (data.canApplyToExpenses !== undefined) taxRate.CanApplyToExpenses = data.canApplyToExpenses;
      if (data.canApplyToLiabilities !== undefined) taxRate.CanApplyToLiabilities = data.canApplyToLiabilities;
      if (data.canApplyToRevenue !== undefined) taxRate.CanApplyToRevenue = data.canApplyToRevenue;
      if (data.displayTaxRate !== undefined) taxRate.DisplayTaxRate = data.displayTaxRate;
      if (data.effectiveRate !== undefined) taxRate.EffectiveRate = data.effectiveRate;
      if (data.taxComponents) taxRate.TaxComponents = data.taxComponents;
      
      return await client.createTaxRate(taxRate);
    }

    case 'xero_update_tax_rate': {
      const schema = z.object({
        taxType: z.string(),
        name: z.string().optional(),
        status: z.enum(['ACTIVE', 'DELETED', 'ARCHIVED']).optional(),
        taxComponents: z.array(TaxComponentSchema).optional()
      });
      const data = schema.parse(args);
      
      // Note: Xero API doesn't have a direct update endpoint for tax rates
      // This would typically require deleting and recreating or using a different approach
      return {
        message: 'Tax rate update requested',
        note: 'Xero tax rates have limited update capabilities. Some changes may require creating a new tax rate.',
        taxType: data.taxType,
        updates: {
          name: data.name,
          status: data.status,
          taxComponents: data.taxComponents
        }
      };
    }

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