import { Injectable } from '@nestjs/common'
import stripe from 'stripe'
import { STRIPE_OPTIONS } from '../../../config'

@Injectable()
export class StripeService {
	private readonly stripeClient: stripe

	constructor() {
		const apiKey = STRIPE_OPTIONS.API_KEY
		if (!apiKey) {
			throw new Error('Please provide Stripe API key')
		}

		this.stripeClient = new stripe(apiKey, { apiVersion: '2026-03-25.dahlia' })
	}

	async createConnectedAccount(tenantId: string): Promise<stripe.Account> {
		return this.stripeClient.accounts.create({ type: 'standard', metadata: { tenantId } })
	}

	async getAccountOnBoardingUrl(accountId: string, refreshUrl: string, redirectUrl: string): Promise<string> {
		return this.stripeClient.accountLinks
			.create({
				account: accountId,
				refresh_url: refreshUrl,
				return_url: redirectUrl,
				type: 'account_onboarding',
			})
			.then((accountLink) => accountLink.url)
	}

	async getAccountInfo(accountId: string): Promise<stripe.Account> {
		return this.stripeClient.accounts.retrieve({}, { stripeAccount: accountId })
	}

	async createPaymentIntent(
		amount: number,
		currency: string,
		accountId: string,
	): Promise<{ id: string; clientSecret: string }> {
		amount = Number.parseFloat((amount * 100).toFixed(4))

		return this.stripeClient.paymentIntents
			.create({
				amount,
				currency,
				automatic_payment_methods: { enabled: true },
				transfer_data: { destination: accountId },
			})
			.then((paymentIntent) => ({ id: paymentIntent.id, clientSecret: paymentIntent.client_secret! }))
	}
}
