import {
  Controller,
  Post,
  Get,
  Body,
  Req,
  UseGuards,
  HttpCode,
  HttpStatus,
  HttpException,
} from '@nestjs/common';
import { BillingService } from './billing.service';
import { AuthGuard } from '../auth/auth.guard';
import { SensitiveRateLimitGuard } from '@/middleware/sensitive-rate-limit.guard';
import { AttestationGuard } from '@/middleware/attestation.guard';
import { type VerifyPurchaseInput } from './billing.types';

@Controller('billing')
export class BillingController {
  constructor(private readonly billingService: BillingService) {}

  @Post('verify')
  @UseGuards(AuthGuard, SensitiveRateLimitGuard, AttestationGuard)
  @HttpCode(HttpStatus.OK)
  async verifyPurchase(@Body() body: VerifyPurchaseInput, @Req() req: any) {
    const input: VerifyPurchaseInput = {
      ...body,
      user_id: req.user.id,
    };
    try {
      return await this.billingService.verifyPurchase(input);
    } catch (error) {
      if (error instanceof HttpException) throw error;
      const message = String((error as any)?.message || 'Failed to verify purchase');
      const lowerMessage = message.toLowerCase();
      const isAppleTransactionNotFound =
        lowerMessage.includes('4040010') || lowerMessage.includes('transaction id not found');

      throw new HttpException(
        {
          status: false,
          statusCode: isAppleTransactionNotFound
            ? HttpStatus.UNPROCESSABLE_ENTITY
            : HttpStatus.INTERNAL_SERVER_ERROR,
          code: isAppleTransactionNotFound ? 'APPLE_TRANSACTION_NOT_FOUND' : undefined,
          message,
        },
        isAppleTransactionNotFound ? HttpStatus.UNPROCESSABLE_ENTITY : HttpStatus.INTERNAL_SERVER_ERROR,
      );
    }
  }

  @Get('subscription')
  @UseGuards(AuthGuard)
  @HttpCode(HttpStatus.OK)
  async getUserSubscription(@Req() req: any) {
    return this.billingService.getUserSubscription(req.user.id);
  }

  @Get('history')
  @UseGuards(AuthGuard)
  @HttpCode(HttpStatus.OK)
  async getPurchaseHistory(@Req() req: any) {
    return this.billingService.getPurchaseHistory(req.user.id);
  }
}
