import { Injectable, Logger } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';

@Injectable()
export class TossPaymentsService {
  private readonly logger = new Logger(TossPaymentsService.name);
  private readonly baseUrl = 'https://api.tosspayments.com';
  private readonly secretKey: string;

  constructor(private configService: ConfigService) {
    this.secretKey = this.configService.get('TOSS_SECRET_KEY') || '';
  }

  private getAuthHeader(): string {
    return 'Basic ' + Buffer.from(this.secretKey + ':').toString('base64');
  }

  async issueBillingKey(authKey: string, customerKey: string): Promise<any> {
    const res = await fetch(`${this.baseUrl}/v1/billing/authorizations/issue`, {
      method: 'POST',
      headers: {
        Authorization: this.getAuthHeader(),
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ authKey, customerKey }),
    });
    if (!res.ok) {
      const err = await res.json();
      this.logger.error('issueBillingKey failed', JSON.stringify(err));
      throw err;
    }
    return res.json();
  }

  async chargeBillingKey(
    billingKey: string,
    customerKey: string,
    amount: number,
    orderName: string,
    orderId: string,
  ): Promise<any> {
    const res = await fetch(`${this.baseUrl}/v1/billing/${billingKey}`, {
      method: 'POST',
      headers: {
        Authorization: this.getAuthHeader(),
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ customerKey, amount, orderId, orderName }),
    });
    if (!res.ok) {
      const err = await res.json();
      this.logger.error('chargeBillingKey failed', JSON.stringify(err));
      throw err;
    }
    return res.json();
  }

  async confirmPayment(paymentKey: string, orderId: string, amount: number): Promise<any> {
    const res = await fetch(`${this.baseUrl}/v1/payments/confirm`, {
      method: 'POST',
      headers: {
        Authorization: this.getAuthHeader(),
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ paymentKey, orderId, amount }),
    });
    if (!res.ok) {
      const err = await res.json();
      this.logger.error('confirmPayment failed', JSON.stringify(err));
      throw err;
    }
    return res.json();
  }

  async getPayment(paymentKey: string): Promise<any> {
    const res = await fetch(`${this.baseUrl}/v1/payments/${paymentKey}`, {
      headers: { Authorization: this.getAuthHeader() },
    });
    if (!res.ok) {
      const err = await res.json();
      this.logger.error('getPayment failed', JSON.stringify(err));
      throw err;
    }
    return res.json();
  }
}
