import { Body, Controller, Get, Logger, Post, Query, UseGuards } from '@nestjs/common';
import { PaymentService } from './services/payment.service';
import { ApiBearerAuth, ApiBody, ApiQuery, ApiTags } from '@nestjs/swagger';
import { JwtAuthGuard } from 'src/guards/jwt-auth.guard';
import { RolesGuard } from 'src/guards/roles.guard';
import { USER_ROLE } from '../users/users.constant';
import { Roles } from 'src/common/decorators/roles.decorator';
import { ResponseMessage } from 'src/common/decorators/response_message.decorator';
import { CurrentUser } from 'src/common/decorators/user.decorator';
import { IFullUser } from '../users/users.interface';
import { CreatePaymentLinkDto } from './payment.validations';

@ApiTags('Payment Endpoints')
@Controller('payment')
@ApiBearerAuth()
export class PaymentController {
	
	private logger: Logger

	constructor(
		private readonly service: PaymentService,
	) {
		this.logger = new Logger(PaymentController.name)
	}

	@Post("subscribe")
	@ApiBody({ type: CreatePaymentLinkDto })
	@UseGuards(JwtAuthGuard, RolesGuard)
	@Roles(USER_ROLE.user, USER_ROLE.admin, USER_ROLE.super_admin)
	@ResponseMessage('Subscribing to a plan')
	async createLink(
		@Body() body: CreatePaymentLinkDto,
		@CurrentUser() user: IFullUser,
	) {
		const res = await this.service.subscibe(body, user)
		
		// check if the response is an error
		if (res.error) {
			this.logger.error(res.error)
			
			// return an error code with the error message
			let statusCode = 400
			throw { statusCode, message: res.error }
		}
		return res

	}

	@Post("cancel-subscription")
	@UseGuards(JwtAuthGuard, RolesGuard)
	@Roles(USER_ROLE.user, USER_ROLE.admin, USER_ROLE.super_admin)
	@ResponseMessage('Cancelling subscription')
	async cancelSubscription(
		@CurrentUser() user: IFullUser,
	) {
		const res = await this.service.cancelSubscription(user)
		// check if sucsseded
		if (res.error) {
			this.logger.error(res.error)
			let statusCode = 400
			throw { statusCode, message: res.error }
		}
		return res
	}
 
	@Post('payme-callback')
	async incomingPayment(
		@Body() body: any,
		@CurrentUser() user: IFullUser,
	) {
		try {
			const res = await this.service.payMeCallback(body)
			return res
		}
		catch (error) {
			this.logger.error(error)
			throw error
		}
	}
}
