import { TenantHeaderInterceptor } from '@backend/auth'
import { BillingProfileRepository, SettingsRepository } from '@backend/repository'
import { Body, Controller, ForbiddenException, HttpCode, Post, UseInterceptors } from '@nestjs/common'
import { ApiOperation, ApiResponse, ApiTags } from '@nestjs/swagger'
import { StripeService } from '../services'
import { CreatePaymentIntentRequest, CreatePaymentIntentResponse } from '../types'

@UseInterceptors(TenantHeaderInterceptor)
@Controller('customer/payment')
@ApiTags('customer')
export class CustomerPaymentController {
	constructor(
		private readonly _stripeService: StripeService,
		private readonly _settingsRepository: SettingsRepository,
		private readonly _billingProfileRepository: BillingProfileRepository,
	) {}

	@Post('intent')
	@HttpCode(200)
	@ApiOperation({ description: 'Create a payment intent for the current tenant' })
	@ApiResponse({
		status: 200,
		type: CreatePaymentIntentResponse,
	})
	async createPaymentIntent(@Body() dto: CreatePaymentIntentRequest): Promise<CreatePaymentIntentResponse> {
		const profile = await this._billingProfileRepository.findOne({ select: { stripeAccountId: true } })
		if (!profile) throw new ForbiddenException('Tenant has not setup online payment')

		const currencyCode = await this._settingsRepository
			.findOne({ select: { billing: { currencyCode: true } } })
			.then((settings) => settings!.billing.currencyCode)

		return this._stripeService.createPaymentIntent(dto.amount, currencyCode, profile.stripeAccountId)
	}
}
