// ============================================================
// VAPI MODULE
// Integração com o v.api para geração de títulos de pagamento
// (PIX, boleto, link de cartão) e consulta de status.
// ============================================================
import { Injectable, Logger, Module } from '@nestjs/common';
import { ConfigModule, ConfigService } from '@nestjs/config';

export interface VapiChargeResult {
  id: string;
  status: string;
  pixCopyPaste?: string;
  pixTxid?: string;
  boletoUrl?: string;
  boletoBarcode?: string;
  cardLinkUrl?: string;
  expiresAt?: string;
}

@Injectable()
export class VapiService {
  private readonly logger = new Logger(VapiService.name);

  constructor(private readonly config: ConfigService) {}

  private get baseUrl(): string {
    return this.config.get<string>('VAPI_URL', 'http://localhost:8000');
  }

  async createCharge(params: {
    apiKey: string;
    chargeType: 'pix' | 'boleto' | 'card';
    amount: number;       // R$ (ex: 150.00)
    dueDate?: string;     // YYYY-MM-DD
    externalRef: string;
    payerName?: string;
    payerDocument?: string;
    payerEmail?: string;
    description?: string;
    pixKey?: string;
    merchantName?: string;
    merchantCity?: string;
    expiresInHours?: number;
  }): Promise<VapiChargeResult> {
    const amountCents = Math.round(params.amount * 100);

    const body: Record<string, unknown> = {
      charge_type:      params.chargeType,
      amount:           amountCents,
      due_date:         params.dueDate,
      external_ref:     params.externalRef,
      payer_name:       params.payerName,
      payer_document:   params.payerDocument,
      payer_email:      params.payerEmail,
      description:      params.description,
      expires_in_hours: params.expiresInHours ?? 24,
    };

    if (params.chargeType === 'pix') {
      body.pix_key      = params.pixKey;
      body.merchant_name = params.merchantName;
      body.merchant_city = params.merchantCity;
    }

    const response = await fetch(`${this.baseUrl}/v1/charges`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        Authorization:  `Bearer ${params.apiKey}`,
      },
      body: JSON.stringify(body),
    });

    if (!response.ok) {
      const text = await response.text().catch(() => response.statusText);
      this.logger.error(`v.api createCharge ${response.status}: ${text}`);
      throw new Error(`v.api error ${response.status}: ${text}`);
    }

    const d = await response.json();
    return {
      id:           d.id,
      status:       d.status,
      pixCopyPaste: d.pix_copy_paste ?? undefined,
      pixTxid:      d.pix_txid ?? undefined,
      boletoUrl:    d.boleto_url ?? undefined,
      boletoBarcode: d.boleto_barcode ?? undefined,
      cardLinkUrl:  d.card_link_url ?? undefined,
      expiresAt:    d.expires_at ?? undefined,
    };
  }

  async getCharge(apiKey: string, vapiChargeId: string): Promise<{ status: string; paidAt?: string }> {
    const response = await fetch(`${this.baseUrl}/v1/charges/${vapiChargeId}`, {
      headers: { Authorization: `Bearer ${apiKey}` },
    });

    if (!response.ok) {
      throw new Error(`v.api getCharge ${response.status}`);
    }

    const d = await response.json();
    return { status: d.status, paidAt: d.paid_at ?? undefined };
  }
}

@Module({
  imports: [ConfigModule],
  providers: [VapiService],
  exports: [VapiService],
})
export class VapiModule {}
