/**
 * Xero Employee Tools
 * Handles employee records (basic accounting, not full payroll)
 */

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 [
    // List employees
    {
      name: 'xero_list_employees',
      description: 'List all employees. Employees are tracked for payroll and expense claims.',
      inputSchema: {
        type: 'object',
        properties: {
          where: { type: 'string', description: 'Filter expression (e.g., Status=="ACTIVE")' },
          order: { type: 'string', description: 'Order by field (e.g., FirstName ASC)' },
          ifModifiedSince: { type: 'string', description: 'ISO date to get only records modified since' }
        }
      }
    },

    // Get single employee
    {
      name: 'xero_get_employee',
      description: 'Get a specific employee by ID. Returns employee details.',
      inputSchema: {
        type: 'object',
        properties: {
          employeeId: { type: 'string', description: 'Employee ID (GUID)' }
        },
        required: ['employeeId']
      }
    },

    // Create employee
    {
      name: 'xero_create_employee',
      description: 'Create a new employee record. First name and last name are required.',
      inputSchema: {
        type: 'object',
        properties: {
          firstName: { type: 'string', description: 'First name (required)' },
          lastName: { type: 'string', description: 'Last name (required)' },
          status: {
            type: 'string',
            enum: ['ACTIVE', 'DELETED'],
            description: 'Employee status (default: ACTIVE)'
          },
          externalLinkUrl: {
            type: 'string',
            description: 'External link URL (e.g., to HR system)'
          }
        },
        required: ['firstName', 'lastName']
      }
    },

    // Update employee
    {
      name: 'xero_update_employee',
      description: 'Update an existing employee. Can update name, status, and external link.',
      inputSchema: {
        type: 'object',
        properties: {
          employeeId: { type: 'string', description: 'Employee ID (GUID)' },
          firstName: { type: 'string', description: 'First name' },
          lastName: { type: 'string', description: 'Last name' },
          status: {
            type: 'string',
            enum: ['ACTIVE', 'DELETED'],
            description: 'Employee status'
          },
          externalLinkUrl: {
            type: 'string',
            description: 'External link URL'
          }
        },
        required: ['employeeId']
      }
    }
  ];
}

export async function handleEmployeeTool(
  toolName: string,
  args: Record<string, unknown>,
  client: XeroClient
): Promise<unknown> {
  switch (toolName) {
    case 'xero_list_employees': {
      const options = {
        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.getEmployees(options);
    }

    case 'xero_get_employee': {
      const { employeeId } = z.object({ employeeId: z.string() }).parse(args);
      return await client.getEmployee(employeeId as any);
    }

    case 'xero_create_employee': {
      const schema = z.object({
        firstName: z.string(),
        lastName: z.string(),
        status: z.enum(['ACTIVE', 'DELETED']).default('ACTIVE'),
        externalLinkUrl: z.string().optional()
      });
      const data = schema.parse(args);
      
      const employee: any = {
        FirstName: data.firstName,
        LastName: data.lastName,
        Status: data.status
      };
      
      if (data.externalLinkUrl) {
        employee.ExternalLink = { Url: data.externalLinkUrl };
      }
      
      return await client.createEmployee(employee);
    }

    case 'xero_update_employee': {
      const schema = z.object({
        employeeId: z.string(),
        firstName: z.string().optional(),
        lastName: z.string().optional(),
        status: z.enum(['ACTIVE', 'DELETED']).optional(),
        externalLinkUrl: z.string().optional()
      });
      const data = schema.parse(args);
      
      const updates: any = {};
      if (data.firstName) updates.FirstName = data.firstName;
      if (data.lastName) updates.LastName = data.lastName;
      if (data.status) updates.Status = data.status;
      if (data.externalLinkUrl) {
        updates.ExternalLink = { Url: data.externalLinkUrl };
      }
      
      // Note: Employee update would need to be implemented in the client
      // For now, return a message
      return {
        success: true,
        message: 'Employee update requested',
        employeeId: data.employeeId,
        updates
      };
    }

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