const Razorpay = require('razorpay');
const appConfig = require('../config/app');

class PaymentService {
  constructor() {
    if (appConfig.razorpayKeyId && appConfig.razorpayKeySecret) {
      this.razorpay = new Razorpay({
        key_id: appConfig.razorpayKeyId,
        key_secret: appConfig.razorpayKeySecret,
      });
    }
  }

  async createOrder(amount, currency = 'INR', receipt = null) {
    if (!this.razorpay) {
      throw new Error('Razorpay not configured. Set RAZORPAY_KEY_ID and RAZORPAY_KEY_SECRET in .env');
    }
    const options = {
      amount: Math.round(amount * 100),
      currency,
      receipt: receipt || 'receipt_' + Date.now(),
    };
    const order = await this.razorpay.orders.create(options);
    return order;
  }

  verifyPayment(orderId, paymentId, signature) {
    const crypto = require('crypto');
    const expectedSignature = crypto
      .createHmac('sha256', appConfig.razorpayKeySecret)
      .update(orderId + '|' + paymentId)
      .digest('hex');
    return expectedSignature === signature;
  }

  async getPaymentDetails(paymentId) {
    if (!this.razorpay) throw new Error('Razorpay not configured.');
    return this.razorpay.payments.fetch(paymentId);
  }
}

module.exports = new PaymentService();
