import { Injectable, NotFoundException } from '@nestjs/common';
import Stripe from 'stripe';
import { ConfigService } from '@nestjs/config';

@Injectable()
export class PaymentService {
  private stripe: Stripe;

  constructor(private config: ConfigService) {
    this.stripe = new Stripe(this.config.get<string>('STRIPE_SECRET_KEY')!, {
      apiVersion: '2025-12-15.clover',
    });
  }

  async createCheckoutSession(data: {
    title: string;
    description?: string;
    amount: number;
  }) {
    const currency = this.config.get<string>('CURRENCY') ?? 'usd';

    const session = await this.stripe.checkout.sessions.create({
      mode: 'payment',
      payment_method_types: ['card', 'link'],
      line_items: [
        {
          price_data: {
            currency,
            unit_amount: Math.round(data.amount * 100),
            product_data: {
              name: data.title,
              description: data.description,
            },
          },
          quantity: 1,
        },
      ],
      success_url: `${this.config.get('APP_URL')}/billing/success?session_id={CHECKOUT_SESSION_ID}`,
      cancel_url: `${this.config.get('APP_URL')}/billing/cancel`,
    });

    return { url: session.url };
  }

  async confirmSession(sessionId: string) {
    if (!sessionId) throw new NotFoundException('Session ID is required');

    const session = await this.stripe.checkout.sessions.retrieve(sessionId);

    if (!session) throw new NotFoundException('Session not found');

    return {
      status: session.payment_status,
      amount: session.amount_total
        ? session.amount_total / 100
        : null,
      currency: session.currency,
      customer_email: session.customer_details?.email,
    };
  }
}
