/**
 * Xero Bill Tools
 * Handles bills (AP invoices/payables) - same structure as invoices but Type=ACCPAY
 */

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

const LineItemSchema = z.object({
  Description: z.string().optional(),
  Quantity: z.number().optional(),
  UnitAmount: z.number().optional(),
  ItemCode: z.string().optional(),
  AccountCode: z.string().optional(),
  TaxType: z.string().optional(),
  DiscountRate: z.number().optional(),
  LineAmount: z.number().optional()
});

const ContactSchema = z.object({
  ContactID: z.string().optional(),
  Name: z.string().optional()
});

export function getTools(_client: XeroClient): Tool[] {
  return [
    // List bills
    {
      name: 'xero_list_bills',
      description: 'List all bills (accounts payable invoices). Bills are Type=ACCPAY invoices.',
      inputSchema: {
        type: 'object',
        properties: {
          page: { type: 'number', description: 'Page number (default 1)' },
          pageSize: { type: 'number', description: 'Page size (max 100)' },
          where: { type: 'string', description: 'Filter expression (e.g., Status=="AUTHORISED")' },
          order: { type: 'string', description: 'Order by field (e.g., Date DESC)' },
          includeArchived: { type: 'boolean', description: 'Include archived bills' },
          ifModifiedSince: { type: 'string', description: 'ISO date to get only records modified since' }
        }
      }
    },

    // Get single bill
    {
      name: 'xero_get_bill',
      description: 'Get a specific bill by ID. Returns full bill details including line items.',
      inputSchema: {
        type: 'object',
        properties: {
          billId: { type: 'string', description: 'Bill/Invoice ID (GUID)' }
        },
        required: ['billId']
      }
    },

    // Create bill
    {
      name: 'xero_create_bill',
      description: 'Create a new bill (accounts payable invoice). This is an invoice you need to pay to a supplier.',
      inputSchema: {
        type: 'object',
        properties: {
          contact: {
            type: 'object',
            properties: {
              ContactID: { type: 'string', description: 'Supplier contact ID (GUID)' },
              Name: { type: 'string', description: 'Supplier name' }
            },
            description: 'Supplier contact'
          },
          lineItems: {
            type: 'array',
            items: {
              type: 'object',
              properties: {
                Description: { type: 'string' },
                Quantity: { type: 'number' },
                UnitAmount: { type: 'number' },
                AccountCode: { type: 'string' },
                TaxType: { type: 'string' }
              }
            },
            description: 'Line items (at least one required)'
          },
          date: { type: 'string', description: 'Bill date (YYYY-MM-DD)' },
          dueDate: { type: 'string', description: 'Due date (YYYY-MM-DD)' },
          reference: { type: 'string', description: 'Supplier invoice number or reference' },
          invoiceNumber: { type: 'string', description: 'Your internal bill number (optional)' },
          status: {
            type: 'string',
            enum: ['DRAFT', 'AUTHORISED'],
            description: 'Bill status (default: DRAFT)'
          },
          lineAmountTypes: {
            type: 'string',
            enum: ['Exclusive', 'Inclusive', 'NoTax'],
            description: 'How line amounts are calculated (default: Exclusive)'
          },
          currencyCode: { type: 'string', description: 'Currency code (e.g., USD)' }
        },
        required: ['contact', 'lineItems']
      }
    },

    // Update bill
    {
      name: 'xero_update_bill',
      description: 'Update an existing bill. Can update status, reference, due date, and line items.',
      inputSchema: {
        type: 'object',
        properties: {
          billId: { type: 'string', description: 'Bill/Invoice ID (GUID)' },
          status: {
            type: 'string',
            enum: ['DRAFT', 'AUTHORISED', 'SUBMITTED'],
            description: 'New status'
          },
          reference: { type: 'string', description: 'Reference text' },
          dueDate: { type: 'string', description: 'Due date (YYYY-MM-DD)' },
          lineItems: {
            type: 'array',
            items: {
              type: 'object',
              properties: {
                Description: { type: 'string' },
                Quantity: { type: 'number' },
                UnitAmount: { type: 'number' },
                AccountCode: { type: 'string' }
              }
            }
          }
        },
        required: ['billId']
      }
    },

    // Void bill
    {
      name: 'xero_void_bill',
      description: 'Void a bill. This sets the status to VOIDED. Cannot be undone.',
      inputSchema: {
        type: 'object',
        properties: {
          billId: { type: 'string', description: 'Bill/Invoice ID (GUID)' }
        },
        required: ['billId']
      }
    },

    // Delete bill
    {
      name: 'xero_delete_bill',
      description: 'Delete a DRAFT bill. Only DRAFT bills can be deleted.',
      inputSchema: {
        type: 'object',
        properties: {
          billId: { type: 'string', description: 'Bill/Invoice ID (GUID)' }
        },
        required: ['billId']
      }
    }
  ];
}

export async function handleBillTool(
  toolName: string,
  args: Record<string, unknown>,
  client: XeroClient
): Promise<unknown> {
  switch (toolName) {
    case 'xero_list_bills': {
      // Add Type==ACCPAY to the where clause to get only bills
      const where = args.where 
        ? `(${args.where}) AND Type=="ACCPAY"`
        : 'Type=="ACCPAY"';
      
      const options = {
        page: args.page as number | undefined,
        pageSize: args.pageSize as number | undefined,
        where,
        order: args.order as string | undefined,
        includeArchived: args.includeArchived as boolean | undefined,
        ifModifiedSince: args.ifModifiedSince ? new Date(args.ifModifiedSince as string) : undefined
      };
      return await client.getInvoices(options);
    }

    case 'xero_get_bill': {
      const { billId } = z.object({ billId: z.string() }).parse(args);
      return await client.getInvoice(billId as any);
    }

    case 'xero_create_bill': {
      const schema = z.object({
        contact: ContactSchema,
        lineItems: z.array(LineItemSchema).min(1),
        date: z.string().optional(),
        dueDate: z.string().optional(),
        reference: z.string().optional(),
        invoiceNumber: z.string().optional(),
        status: z.enum(['DRAFT', 'AUTHORISED']).default('DRAFT'),
        lineAmountTypes: z.enum(['Exclusive', 'Inclusive', 'NoTax']).default('Exclusive'),
        currencyCode: z.string().optional()
      });
      const data = schema.parse(args);
      
      const bill: any = {
        Type: 'ACCPAY', // Bills are ACCPAY type
        Contact: data.contact,
        LineItems: data.lineItems,
        Status: data.status,
        LineAmountTypes: data.lineAmountTypes
      };
      
      if (data.date) bill.Date = data.date;
      if (data.dueDate) bill.DueDate = data.dueDate;
      if (data.reference) bill.Reference = data.reference;
      if (data.invoiceNumber) bill.InvoiceNumber = data.invoiceNumber;
      if (data.currencyCode) bill.CurrencyCode = data.currencyCode;
      
      return await client.createInvoice(bill);
    }

    case 'xero_update_bill': {
      const schema = z.object({
        billId: z.string(),
        status: z.enum(['DRAFT', 'AUTHORISED', 'SUBMITTED']).optional(),
        reference: z.string().optional(),
        dueDate: z.string().optional(),
        lineItems: z.array(LineItemSchema).optional()
      });
      const data = schema.parse(args);
      
      const updates: any = {};
      if (data.status) updates.Status = data.status;
      if (data.reference) updates.Reference = data.reference;
      if (data.dueDate) updates.DueDate = data.dueDate;
      if (data.lineItems) updates.LineItems = data.lineItems;
      
      return await client.updateInvoice(data.billId as any, updates);
    }

    case 'xero_void_bill': {
      const { billId } = z.object({ billId: z.string() }).parse(args);
      return await client.updateInvoice(billId as any, { Status: 'VOIDED' as any });
    }

    case 'xero_delete_bill': {
      const { billId } = z.object({ billId: z.string() }).parse(args);
      await client.deleteInvoice(billId as any);
      return { success: true, message: 'Bill deleted' };
    }

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