import {
  McpToolProvider,
  McpToolDefinition,
  McpToolHandler,
  McpContext,
} from '../interfaces';

/**
 * Fiados (Credit) Tools Service
 * Provides MCP tools for credit/fiado management.
 *
 * TODO: Connect to actual FiadosService when available.
 */
export class FiadosToolsService implements McpToolProvider {
  getTools(): McpToolDefinition[] {
    return [
      {
        name: 'get_fiado_balance',
        description: 'Consulta el saldo de credito de un cliente',
        category: 'fiados',
        parameters: {
          type: 'object',
          properties: {
            customer_id: { type: 'string', format: 'uuid' },
          },
          required: ['customer_id'],
        },
        returns: { type: 'object' },
      },
      {
        name: 'create_fiado',
        description: 'Registra una venta a credito (fiado)',
        category: 'fiados',
        permissions: ['fiados.create'],
        parameters: {
          type: 'object',
          properties: {
            customer_id: { type: 'string', format: 'uuid' },
            amount: { type: 'number', minimum: 0.01 },
            order_id: { type: 'string', format: 'uuid' },
            description: { type: 'string' },
          },
          required: ['customer_id', 'amount'],
        },
        returns: { type: 'object' },
      },
      {
        name: 'register_fiado_payment',
        description: 'Registra un abono a la cuenta de credito',
        category: 'fiados',
        permissions: ['fiados.payment'],
        parameters: {
          type: 'object',
          properties: {
            customer_id: { type: 'string', format: 'uuid' },
            amount: { type: 'number', minimum: 0.01 },
            payment_method: { type: 'string', enum: ['cash', 'card', 'transfer'] },
          },
          required: ['customer_id', 'amount'],
        },
        returns: { type: 'object' },
      },
      {
        name: 'check_fiado_eligibility',
        description: 'Verifica si un cliente puede comprar a credito',
        category: 'fiados',
        parameters: {
          type: 'object',
          properties: {
            customer_id: { type: 'string', format: 'uuid' },
            amount: { type: 'number', minimum: 0.01 },
          },
          required: ['customer_id', 'amount'],
        },
        returns: {
          type: 'object',
          properties: {
            eligible: { type: 'boolean' },
            reason: { type: 'string' },
          },
        },
      },
    ];
  }

  getHandler(toolName: string): McpToolHandler | undefined {
    const handlers: Record<string, McpToolHandler> = {
      get_fiado_balance: this.getFiadoBalance.bind(this),
      create_fiado: this.createFiado.bind(this),
      register_fiado_payment: this.registerFiadoPayment.bind(this),
      check_fiado_eligibility: this.checkFiadoEligibility.bind(this),
    };
    return handlers[toolName];
  }

  private async getFiadoBalance(
    params: { customer_id: string },
    context: McpContext
  ): Promise<any> {
    // TODO: Connect to actual fiados service
    return {
      customer_id: params.customer_id,
      customer_name: 'Cliente ejemplo',
      balance: 1500.00,
      credit_limit: 5000.00,
      available_credit: 3500.00,
      pending_fiados: [
        { id: 'fiado-1', amount: 500.00, date: '2026-01-10', status: 'pending' },
        { id: 'fiado-2', amount: 1000.00, date: '2026-01-05', status: 'pending' },
      ],
      recent_payments: [],
      message: 'Conectar a FiadosService real',
    };
  }

  private async createFiado(
    params: { customer_id: string; amount: number; order_id?: string; description?: string },
    context: McpContext
  ): Promise<any> {
    // TODO: Connect to actual fiados service
    // First check eligibility
    const eligibility = await this.checkFiadoEligibility(
      { customer_id: params.customer_id, amount: params.amount },
      context
    );

    if (!eligibility.eligible) {
      throw new Error(eligibility.reason);
    }

    return {
      fiado_id: 'fiado-' + Date.now(),
      customer_id: params.customer_id,
      amount: params.amount,
      order_id: params.order_id,
      description: params.description,
      due_date: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000).toISOString(), // 30 days
      new_balance: 1500.00 + params.amount,
      remaining_credit: 3500.00 - params.amount,
      created_by: context.userId,
      created_at: new Date().toISOString(),
      message: 'Conectar a FiadosService real',
    };
  }

  private async registerFiadoPayment(
    params: { customer_id: string; amount: number; payment_method?: string },
    context: McpContext
  ): Promise<any> {
    // TODO: Connect to actual fiados service
    return {
      payment_id: 'payment-' + Date.now(),
      customer_id: params.customer_id,
      amount: params.amount,
      payment_method: params.payment_method || 'cash',
      previous_balance: 1500.00,
      new_balance: 1500.00 - params.amount,
      fiados_paid: [],
      created_by: context.userId,
      created_at: new Date().toISOString(),
      message: 'Conectar a FiadosService real',
    };
  }

  private async checkFiadoEligibility(
    params: { customer_id: string; amount: number },
    context: McpContext
  ): Promise<any> {
    // TODO: Connect to actual fiados service
    const mockBalance = 1500.00;
    const mockCreditLimit = 5000.00;
    const mockAvailableCredit = mockCreditLimit - mockBalance;
    const hasOverdue = false;

    if (hasOverdue) {
      return {
        eligible: false,
        reason: 'Cliente tiene saldo vencido',
        current_balance: mockBalance,
        credit_limit: mockCreditLimit,
        available_credit: mockAvailableCredit,
        requested_amount: params.amount,
        has_overdue: true,
        suggestions: ['Solicitar pago del saldo vencido antes de continuar'],
      };
    }

    if (params.amount > mockAvailableCredit) {
      return {
        eligible: false,
        reason: 'Monto excede credito disponible',
        current_balance: mockBalance,
        credit_limit: mockCreditLimit,
        available_credit: mockAvailableCredit,
        requested_amount: params.amount,
        has_overdue: false,
        suggestions: [
          `Reducir el monto a $${mockAvailableCredit.toFixed(2)}`,
          'Solicitar aumento de limite de credito',
        ],
      };
    }

    return {
      eligible: true,
      reason: 'Cliente con credito disponible',
      current_balance: mockBalance,
      credit_limit: mockCreditLimit,
      available_credit: mockAvailableCredit,
      requested_amount: params.amount,
      has_overdue: false,
      suggestions: [],
      message: 'Conectar a FiadosService real',
    };
  }
}
