// src/bot/nowpayments.service.ts
import { Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import axios from 'axios';
import * as crypto from 'crypto';

@Injectable()
export class NowPaymentsService {
  private readonly apiUrl = 'https://api.nowpayments.io/v1';
  private readonly apiKey: string;

  constructor(private configService: ConfigService) {
    this.apiKey = this.configService.get('NOWPAYMENT_API_KEY')!;
  }

  async createPremiumPayment(userId: number) {
    const orderId = `premium_${userId}_${Date.now()}`;
    const ipnUrl = `${this.configService.get('APP_URL')}/api/payments/ipn`;
    const callbackUrl = `${this.configService.get('APP_URL')}/payment-result`;

    const payload = {
      price_amount: 10,
      price_currency: 'usd',
      order_id: orderId,
      order_description: 'Premium Access - Unlimited Test Results',
      ipn_callback_url: ipnUrl,
      success_url: `${callbackUrl}?status=success`,
      cancel_url: `${callbackUrl}?status=cancel`
    };

    const response = await axios.post(`${this.apiUrl}/invoice`, payload, {
      headers: {
        'x-api-key': this.apiKey,
        'Content-Type': 'application/json'
      }
    });

    return {
      paymentId: response.data.id,
      paymentUrl: response.data.invoice_url,
      orderId
    };
  }

  verifyIpnSignature(payload: any, signature: string): boolean {
    const secret = this.configService.get('NOWPAYMENT_IPN_SECRET')!;
    const hmac = crypto.createHmac('sha512', secret);
    hmac.update(JSON.stringify(payload));
    const calculatedSignature = hmac.digest('hex');
    return calculatedSignature === signature;
  }
}