import {
  Controller,
  Get,
  Post,
  Body,
  Param,
  HttpCode,
  HttpStatus,
  RawBodyRequest,
  Req,
} from '@nestjs/common';
import { Request } from 'express';
import { PaymentService } from '../../application/services/payment.service';
import { CreatePaymentDto } from '../../application/dtos/payment.dto';
import { PaymentMethod } from '../../domain/entities/payment.entity';

@Controller('payments')
export class PaymentController {
  constructor(private paymentService: PaymentService) {}

  /**
   * Create a payment for an order
   */
  @Post()
  @HttpCode(HttpStatus.CREATED)
  async createPayment(@Body() dto: CreatePaymentDto) {
    const result = await this.paymentService.createPayment(dto);
    return {
      success: true,
      data: result,
    };
  }

  /**
   * Get payment status
   */
  @Get(':id/status')
  async getPaymentStatus(@Param('id') paymentId: string) {
    const status = await this.paymentService.checkStatus(paymentId);
    return {
      success: true,
      data: status,
    };
  }

  /**
   * Alipay callback
   */
  @Post('alipay/notify')
  @HttpCode(HttpStatus.OK)
  async handleAlipayCallback(@Body() payload: Record<string, unknown>) {
    try {
      await this.paymentService.handleCallback(PaymentMethod.ALIPAY, payload);
      return 'success'; // Alipay expects 'success' as response
    } catch (error) {
      console.error('Alipay callback error:', error);
      return 'fail';
    }
  }

  /**
   * WeChat Pay callback
   */
  @Post('wechat/notify')
  @HttpCode(HttpStatus.OK)
  async handleWechatCallback(
    @Body() payload: Record<string, unknown>,
  ) {
    try {
      await this.paymentService.handleCallback(PaymentMethod.WECHAT, payload);
      return {
        code: 'SUCCESS',
        message: '成功',
      };
    } catch (error) {
      console.error('WeChat Pay callback error:', error);
      return {
        code: 'FAIL',
        message: '失败',
      };
    }
  }

  /**
   * Stripe webhook
   */
  @Post('stripe/webhook')
  @HttpCode(HttpStatus.OK)
  async handleStripeWebhook(
    @Req() req: RawBodyRequest<Request>,
    @Body() payload: Record<string, unknown>,
  ) {
    try {
      // In production, verify webhook signature:
      // const sig = req.headers['stripe-signature'];
      // const event = stripe.webhooks.constructEvent(req.rawBody, sig, webhookSecret);

      await this.paymentService.handleCallback(PaymentMethod.CREDIT_CARD, payload);
      return { received: true };
    } catch (error) {
      console.error('Stripe webhook error:', error);
      return { received: false, error: (error as Error).message };
    }
  }
}
