const { MercadoPagoConfig, Payment } = require('mercadopago');

class MercadoPagoService {
    constructor() {
        if (process.env.MERCADOPAGO_ACCESS_TOKEN) {
            this.client = new MercadoPagoConfig({ 
                accessToken: process.env.MERCADOPAGO_ACCESS_TOKEN,
                options: { timeout: 5000 }
            });
            this.payment = new Payment(this.client);
        }
    }

    async gerarPix(dados) {
        try {
            console.log('🏦 Gerando PIX com dados:', dados);
            console.log('🔑 Access Token:', process.env.MERCADOPAGO_ACCESS_TOKEN ? 'Configurado' : 'NÃO CONFIGURADO');
            
            const payment_data = {
                transaction_amount: parseFloat(dados.valor),
                description: dados.descricao || `Venda #${dados.venda_id} - Liberi Kids`,
                payment_method_id: 'pix',
                payer: {
                    email: dados.cliente_email || 'cliente@liberikids.com',
                    first_name: dados.cliente_nome || 'Cliente',
                    identification: {
                        type: 'CPF',
                        number: dados.cliente_cpf || '00000000000'
                    }
                },
                external_reference: dados.venda_id.toString(),
                // notification_url removida para desenvolvimento local
                date_of_expiration: new Date(Date.now() + 30 * 60 * 1000).toISOString() // 30 minutos
            };

            console.log('📤 Enviando dados para Mercado Pago:', JSON.stringify(payment_data, null, 2));
            const payment = await this.payment.create({ body: payment_data });
            console.log('✅ Resposta do Mercado Pago:', payment);

            return {
                success: true,
                payment_id: payment.id,
                qr_code: payment.point_of_interaction.transaction_data.qr_code,
                qr_code_base64: payment.point_of_interaction.transaction_data.qr_code_base64,
                pix_copy_paste: payment.point_of_interaction.transaction_data.qr_code,
                expiration_date: payment.date_of_expiration,
                transaction_amount: payment.transaction_amount,
                status: payment.status
            };

        } catch (error) {
            console.error('Erro ao gerar PIX:', error);
            return {
                success: false,
                error: error.message
            };
        }
    }

    async createPixPayment(paymentData) {
        try {
            console.log('🏦 Criando PIX Payment:', paymentData);
            console.log('🔑 Access Token:', process.env.MERCADOPAGO_ACCESS_TOKEN ? 'Configurado' : 'NÃO CONFIGURADO');
            
            if (!this.payment) {
                throw new Error('MercadoPago não configurado. Verifique o MERCADOPAGO_ACCESS_TOKEN no .env');
            }

            const payment_data = {
                transaction_amount: parseFloat(paymentData.transaction_amount),
                description: paymentData.description,
                payment_method_id: paymentData.payment_method_id || 'pix',
                payer: paymentData.payer,
                date_of_expiration: new Date(Date.now() + 30 * 60 * 1000).toISOString() // 30 minutos
            };

            if (paymentData.external_reference) {
                payment_data.external_reference = paymentData.external_reference.toString();
            }

            console.log('📤 Enviando dados para Mercado Pago:', JSON.stringify(payment_data, null, 2));
            const payment = await this.payment.create({ body: payment_data });
            console.log('✅ PIX criado com sucesso:', payment.id);

            return payment;

        } catch (error) {
            console.error('❌ Erro ao criar PIX:', error);
            throw error;
        }
    }

    async consultarPagamento(payment_id) {
        try {
            const payment = await this.payment.get({ id: payment_id });
            return {
                success: true,
                status: payment.status,
                status_detail: payment.status_detail,
                transaction_amount: payment.transaction_amount,
                date_approved: payment.date_approved,
                external_reference: payment.external_reference
            };
        } catch (error) {
            console.error('Erro ao consultar pagamento:', error);
            return {
                success: false,
                error: error.message
            };
        }
    }
}

module.exports = new MercadoPagoService();
