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

@Injectable()
export class PaystarService {
  private readonly apiUrl = 'https://core.paystar.ir/api/pardakht';
  private readonly token: string;
  private readonly signKey: string;

  constructor(private configService: ConfigService) {
    this.token = this.configService.get('PAYSTAR_TOKEN')!;
    this.signKey = this.configService.get('PAYSTAR_SIGN_KEY')!;
  }

  async createPremiumPayment(userId: number) {
    const orderId = `premium_${userId}_${Date.now()}`;
    const amount = process.env.TOMAN_PRICE || 10000;
    const callback = `${this.configService.get('PAYSTAR_CALLBACK_BASE')}/api/payments/paystar-callback`;

    const signData = `${amount}#${orderId}#${callback}`;
    const sign = crypto.createHmac('sha512', this.signKey)
      .update(signData)
      .digest('hex');

    const response = await axios.post(`${this.apiUrl}/create`, {
      amount,
      order_id: orderId,
      callback,
      sign
    }, {
      headers: {
        'Authorization': `Bearer ${this.token}`,
        'Content-Type': 'application/json'
      }
    });

    console.log(response.data)
    return {
      paymentUrl: `${this.apiUrl}/payment?token=${response.data.data.token}`,
      orderId,
      token: response.data.token
    };
  }
}