import { Controller, Post, Get, Query, Body, UseGuards, HttpException, HttpStatus } from '@nestjs/common'
import { InjectModel } from '@nestjs/mongoose'
import { Model } from 'mongoose'
import { User, UserDocument } from '../user/user.schema'
import { PaymentOrder, PaymentOrderDocument } from './payment-order.schema'
import { JwtAuthGuard } from '../../common/guards/jwt-auth.guard'
import { CurrentUser } from '../../common/decorators/current-user.decorator'
import { WechatPayService } from './wechat-pay.service'
import { Public } from '../../common/decorators/public.decorator'

const VIP_AMOUNT = 1990 // 19.9 元（分）
const VIP_DURATION_DAYS = 30

@Controller('payment')
export class PaymentController {
  constructor(
    @InjectModel(User.name) private userModel: Model<UserDocument>,
    @InjectModel(PaymentOrder.name) private orderModel: Model<PaymentOrderDocument>,
    private wechatPay: WechatPayService,
  ) {}

  /** 创建订单（H5：Native 扫码支付） */
  @UseGuards(JwtAuthGuard)
  @Post('create')
  async create(@CurrentUser('userId') userId: string) {
    const user = await this.userModel.findById(userId).exec()
    if (!user) throw new HttpException('用户不存在', HttpStatus.NOT_FOUND)
    if (user.plan === 'vip') throw new HttpException('已是会员', HttpStatus.BAD_REQUEST)

    const outTradeNo = `VIP${Date.now()}${userId.slice(-6)}`
    const result = await this.wechatPay.nativePay('AI磁场月度会员', outTradeNo, VIP_AMOUNT)

    // 保存订单
    await this.orderModel.create({
      outTradeNo,
      userId,
      userPhone: user.phone || '',
      amount: VIP_AMOUNT,
      title: 'AI磁场月度会员',
      status: 'pending',
      channel: 'native',
    })

    return {
      outTradeNo,
      codeUrl: result.codeUrl,
      amount: VIP_AMOUNT,
      title: 'AI磁场月度会员',
    }
  }

  /** JSAPI 支付（微信小程序） */
  @UseGuards(JwtAuthGuard)
  @Post('jsapi')
  async jsapi(@CurrentUser('userId') userId: string, @Body('openid') openid: string) {
    const user = await this.userModel.findById(userId).exec()
    if (!user) throw new HttpException('用户不存在', HttpStatus.NOT_FOUND)
    if (!openid) throw new HttpException('缺少 openid', HttpStatus.BAD_REQUEST)
    if (user.plan === 'vip') throw new HttpException('已是会员', HttpStatus.BAD_REQUEST)

    const outTradeNo = `VIP${Date.now()}${userId.slice(-6)}`
    const result = await this.wechatPay.jsapiPay('AI磁场月度会员', outTradeNo, VIP_AMOUNT, openid)

    // 保存订单
    await this.orderModel.create({
      outTradeNo,
      userId,
      userPhone: user.phone || '',
      amount: VIP_AMOUNT,
      title: 'AI磁场月度会员',
      status: 'pending',
      channel: 'jsapi',
    })

    return result
  }

  /** 支付回调通知 */
  @Public()
  @Post('notify')
  async notify(@Body() body: any) {
    try {
      const decrypted = this.wechatPay.verifyAndDecrypt(body, '', '', '')
      if (!decrypted) return { code: 'FAIL', message: '验签失败' }

      const outTradeNo = decrypted.out_trade_no
      const wxTransactionId = decrypted.transaction_id

      // 更新订单状态
      const order = await this.orderModel.findOne({ outTradeNo }).exec()
      if (order && order.status === 'pending') {
        order.status = 'success'
        order.paidAt = new Date()
        order.wxTransactionId = wxTransactionId
        order.description = `${decrypted.trade_type || ''} 支付成功`
        await order.save()
      }

      // 开通会员
      const userId = outTradeNo.slice(-6)
      const user = await this.userModel.findOne({ _id: { $regex: userId + '$' } }).exec()
      if (user && user.plan !== 'vip') {
        const expireAt = new Date()
        expireAt.setDate(expireAt.getDate() + VIP_DURATION_DAYS)
        user.plan = 'vip'
        user.vipExpireAt = expireAt
        user.remaining = 999
        await user.save()
      }
      return { code: 'SUCCESS', message: '成功' }
    } catch {
      return { code: 'FAIL', message: '处理失败' }
    }
  }

  /** 查询订单（微信侧） */
  @UseGuards(JwtAuthGuard)
  @Post('query')
  async query(@Body('outTradeNo') outTradeNo: string) {
    return this.wechatPay.queryOrder(outTradeNo)
  }
}
