/**
 * Xero Purchase Order Tools
 * Handles purchase orders (POs) for ordering goods/services from suppliers
 */

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(),
  LineAmount: z.number().optional()
});

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

export function getTools(_client: XeroClient): Tool[] {
  return [
    // List purchase orders
    {
      name: 'xero_list_purchase_orders',
      description: 'List all purchase orders. Use where clause to filter by Status (DRAFT, SUBMITTED, AUTHORISED, BILLED).',
      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)' },
          ifModifiedSince: { type: 'string', description: 'ISO date to get only records modified since' }
        }
      }
    },

    // Get single purchase order
    {
      name: 'xero_get_purchase_order',
      description: 'Get a specific purchase order by ID. Returns full details including line items.',
      inputSchema: {
        type: 'object',
        properties: {
          purchaseOrderId: { type: 'string', description: 'Purchase order ID (GUID)' }
        },
        required: ['purchaseOrderId']
      }
    },

    // Create purchase order
    {
      name: 'xero_create_purchase_order',
      description: 'Create a new purchase order. Used for ordering goods/services from suppliers.',
      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' },
                ItemCode: { type: 'string' },
                AccountCode: { type: 'string' },
                TaxType: { type: 'string' }
              }
            },
            description: 'Line items (at least one required)'
          },
          date: { type: 'string', description: 'Purchase order date (YYYY-MM-DD)' },
          deliveryDate: { type: 'string', description: 'Expected delivery date (YYYY-MM-DD)' },
          deliveryAddress: { type: 'string', description: 'Delivery address' },
          attentionTo: { type: 'string', description: 'Attention to (person name)' },
          telephone: { type: 'string', description: 'Contact telephone' },
          deliveryInstructions: { type: 'string', description: 'Delivery instructions' },
          reference: { type: 'string', description: 'Reference text' },
          purchaseOrderNumber: { type: 'string', description: 'PO number (optional)' },
          status: {
            type: 'string',
            enum: ['DRAFT', 'SUBMITTED', 'AUTHORISED'],
            description: 'Purchase order 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 purchase order
    {
      name: 'xero_update_purchase_order',
      description: 'Update an existing purchase order. Can update status, delivery details, and line items.',
      inputSchema: {
        type: 'object',
        properties: {
          purchaseOrderId: { type: 'string', description: 'Purchase order ID (GUID)' },
          status: {
            type: 'string',
            enum: ['DRAFT', 'SUBMITTED', 'AUTHORISED', 'BILLED'],
            description: 'New status'
          },
          deliveryDate: { type: 'string', description: 'Expected delivery date (YYYY-MM-DD)' },
          deliveryInstructions: { type: 'string', description: 'Delivery instructions' },
          reference: { type: 'string', description: 'Reference text' },
          lineItems: {
            type: 'array',
            items: {
              type: 'object',
              properties: {
                Description: { type: 'string' },
                Quantity: { type: 'number' },
                UnitAmount: { type: 'number' }
              }
            }
          }
        },
        required: ['purchaseOrderId']
      }
    },

    // Delete purchase order
    {
      name: 'xero_delete_purchase_order',
      description: 'Delete a DRAFT purchase order. Only DRAFT purchase orders can be deleted.',
      inputSchema: {
        type: 'object',
        properties: {
          purchaseOrderId: { type: 'string', description: 'Purchase order ID (GUID)' }
        },
        required: ['purchaseOrderId']
      }
    }
  ];
}

export async function handlePurchaseOrderTool(
  toolName: string,
  args: Record<string, unknown>,
  client: XeroClient
): Promise<unknown> {
  switch (toolName) {
    case 'xero_list_purchase_orders': {
      const options = {
        page: args.page as number | undefined,
        pageSize: args.pageSize as number | undefined,
        where: args.where as string | undefined,
        order: args.order as string | undefined,
        ifModifiedSince: args.ifModifiedSince ? new Date(args.ifModifiedSince as string) : undefined
      };
      return await client.getPurchaseOrders(options);
    }

    case 'xero_get_purchase_order': {
      const { purchaseOrderId } = z.object({ purchaseOrderId: z.string() }).parse(args);
      return await client.getPurchaseOrder(purchaseOrderId as any);
    }

    case 'xero_create_purchase_order': {
      const schema = z.object({
        contact: ContactSchema,
        lineItems: z.array(LineItemSchema).min(1),
        date: z.string().optional(),
        deliveryDate: z.string().optional(),
        deliveryAddress: z.string().optional(),
        attentionTo: z.string().optional(),
        telephone: z.string().optional(),
        deliveryInstructions: z.string().optional(),
        reference: z.string().optional(),
        purchaseOrderNumber: z.string().optional(),
        status: z.enum(['DRAFT', 'SUBMITTED', 'AUTHORISED']).default('DRAFT'),
        lineAmountTypes: z.enum(['Exclusive', 'Inclusive', 'NoTax']).default('Exclusive'),
        currencyCode: z.string().optional()
      });
      const data = schema.parse(args);
      
      const purchaseOrder: any = {
        Contact: data.contact,
        LineItems: data.lineItems,
        Status: data.status,
        LineAmountTypes: data.lineAmountTypes
      };
      
      if (data.date) purchaseOrder.Date = data.date;
      if (data.deliveryDate) purchaseOrder.DeliveryDate = data.deliveryDate;
      if (data.deliveryAddress) purchaseOrder.DeliveryAddress = data.deliveryAddress;
      if (data.attentionTo) purchaseOrder.AttentionTo = data.attentionTo;
      if (data.telephone) purchaseOrder.Telephone = data.telephone;
      if (data.deliveryInstructions) purchaseOrder.DeliveryInstructions = data.deliveryInstructions;
      if (data.reference) purchaseOrder.Reference = data.reference;
      if (data.purchaseOrderNumber) purchaseOrder.PurchaseOrderNumber = data.purchaseOrderNumber;
      if (data.currencyCode) purchaseOrder.CurrencyCode = data.currencyCode;
      
      return await client.createPurchaseOrder(purchaseOrder);
    }

    case 'xero_update_purchase_order': {
      const schema = z.object({
        purchaseOrderId: z.string(),
        status: z.enum(['DRAFT', 'SUBMITTED', 'AUTHORISED', 'BILLED']).optional(),
        deliveryDate: z.string().optional(),
        deliveryInstructions: z.string().optional(),
        reference: 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.deliveryDate) updates.DeliveryDate = data.deliveryDate;
      if (data.deliveryInstructions) updates.DeliveryInstructions = data.deliveryInstructions;
      if (data.reference) updates.Reference = data.reference;
      if (data.lineItems) updates.LineItems = data.lineItems;
      
      return await client.updatePurchaseOrder(data.purchaseOrderId as any, updates);
    }

    case 'xero_delete_purchase_order': {
      const { purchaseOrderId } = z.object({ purchaseOrderId: z.string() }).parse(args);
      // Set status to DELETED
      return await client.updatePurchaseOrder(purchaseOrderId as any, { Status: 'DELETED' as any });
    }

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