import {
  Controller,
  Post,
  Body,
  Get,
  Headers,
  RawBody,
  HttpCode,
  HttpStatus,
  Req,
  Logger,
  BadRequestException,
} from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { ApiTags, ApiOperation, ApiBearerAuth } from '@nestjs/swagger';
import Stripe from 'stripe';
import { BillingService } from './billing.service';
import { Public } from '../../common/decorators';

@ApiTags('Billing')
@Controller('billing')
export class BillingController {
  private readonly logger = new Logger(BillingController.name);
  private readonly stripe: Stripe | null;
  private readonly webhookSecret: string;

  constructor(
    private readonly billingService: BillingService,
    private readonly configService: ConfigService,
  ) {
    const stripeKey = this.configService.get<string>('STRIPE_SECRET_KEY');
    this.webhookSecret = this.configService.get<string>('STRIPE_WEBHOOK_SECRET', '');

    if (stripeKey) {
      this.stripe = new Stripe(stripeKey);
    } else {
      this.stripe = null;
    }
  }

  @Get('plans')
  @Public()
  @ApiOperation({ summary: 'Mevcut planları listele (public)' })
  async getPlans() {
    const plans = await this.billingService.getPlans();
    return plans;
  }

  @Post('checkout')
  @ApiBearerAuth()
  @ApiOperation({ summary: 'Stripe Checkout session oluştur' })
  async createCheckout(
    @Req() req: any,
    @Body() body: { planName: string; billingCycle: 'monthly' | 'yearly' },
  ) {
    const userId = req.user?.id || req.user?.sub;
    return this.billingService.createCheckoutSession(userId, body.planName, body.billingCycle);
  }

  @Get('credits/balance')
  @ApiBearerAuth()
  @ApiOperation({ summary: 'Kredi bakiyesini getir' })
  async getCreditBalance(@Req() req: any) {
    const userId = req.user?.id || req.user?.sub;
    return this.billingService.getCreditBalance(userId);
  }

  @Get('credits/history')
  @ApiBearerAuth()
  @ApiOperation({ summary: 'Kredi işlem geçmişi' })
  async getCreditHistory(@Req() req: any) {
    const userId = req.user?.id || req.user?.sub;
    return this.billingService.getCreditHistory(userId);
  }

  @Get('subscription')
  @ApiBearerAuth()
  @ApiOperation({ summary: 'Aktif abonelik bilgisi' })
  async getSubscription(@Req() req: any) {
    const userId = req.user?.id || req.user?.sub;
    return this.billingService.getActiveSubscription(userId);
  }

  @Post('webhook')
  @Public()
  @HttpCode(HttpStatus.OK)
  @ApiOperation({ summary: 'Stripe webhook handler' })
  async handleWebhook(
    @Headers('stripe-signature') signature: string,
    @RawBody() rawBody: Buffer,
  ) {
    if (!this.stripe || !this.webhookSecret) {
      throw new BadRequestException('Stripe webhook yapılandırılmamış');
    }

    let event: Stripe.Event;

    try {
      event = this.stripe.webhooks.constructEvent(
        rawBody,
        signature,
        this.webhookSecret,
      );
    } catch (err) {
      this.logger.error(`Webhook signature doğrulama hatası: ${err}`);
      throw new BadRequestException('Webhook doğrulama başarısız');
    }

    this.logger.log(`Webhook alındı: ${event.type}`);
    await this.billingService.handleWebhookEvent(event);

    return { received: true };
  }
}
