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

const VIP_DURATION_DAYS = 30

@Controller('admin')
export class AdminController {
  constructor(
    @InjectModel(User.name) private userModel: Model<UserDocument>,
    @InjectModel(Interview.name) private interviewModel: Model<InterviewDocument>,
    @InjectModel(PaymentOrder.name) private orderModel: Model<PaymentOrderDocument>,
    @InjectModel(SiteConfig.name) private configModel: Model<SiteConfigDocument>,
    private wechatPay: WechatPayService,
  ) {}

  @Get('check')
  @UseGuards(JwtAuthGuard)
  async checkAdmin(@CurrentUser('userId') userId: string) {
    const user = await this.userModel.findById(userId).select('role').exec()
    return { isAdmin: user?.role === 'admin' }
  }

  @Public()
  @Post('verify')
  async verify(@Body('adminId') adminId: string) {
    const user = await this.userModel.findById(adminId).exec()
    if (!user || user.role !== 'admin') {
      throw new HttpException('无权限访问', HttpStatus.FORBIDDEN)
    }
    return { ok: true, nickname: user.nickname || '管理员' }
  }

  @Public()
  @Get('overview')
  async overview() {
    const [userCount, interviewCount, todayUsers, todayInterviews] = await Promise.all([
      this.userModel.countDocuments().exec(),
      this.interviewModel.countDocuments().exec(),
      this.userModel.countDocuments({ createdAt: { $gte: new Date(Date.now() - 24 * 60 * 60 * 1000) } }).exec(),
      this.interviewModel.countDocuments({ createdAt: { $gte: new Date(Date.now() - 24 * 60 * 60 * 1000) } }).exec(),
    ])
    return { userCount, interviewCount, todayUsers, todayInterviews }
  }

  @Public()
  @Get('users')
  async getUsers(@Query('keyword') keyword: string, @Query('page') page = '1', @Query('limit') limit = '20') {
    const filter: any = {}
    if (keyword) filter.$or = [
      { phone: { $regex: keyword, $options: 'i' } },
      { nickname: { $regex: keyword, $options: 'i' } },
    ]
    const skip = (Math.max(1, +page) - 1) * +limit
    const [users, total] = await Promise.all([
      this.userModel.find(filter).sort({ createdAt: -1 }).skip(skip).limit(+limit).select('-password').lean().exec(),
      this.userModel.countDocuments(filter).exec(),
    ])
    return { users, total, page: +page }
  }

  @Public()
  @Get('interviews')
  async getInterviews(@Query('page') page = '1', @Query('limit') limit = '20') {
    const skip = (Math.max(1, +page) - 1) * +limit
    const [interviews, total] = await Promise.all([
      this.interviewModel.find().sort({ createdAt: -1 }).skip(skip).limit(+limit).populate('userId', 'phone nickname').lean().exec(),
      this.interviewModel.countDocuments().exec(),
    ])
    return { interviews, total, page: +page }
  }

  @UseGuards(JwtAuthGuard)
  @Post('set-vip')
  async setVip(@Body('userId') targetUserId: string, @CurrentUser('userId') adminUserId: string) {
    const admin = await this.userModel.findById(adminUserId).exec()
    if (admin?.role !== 'admin') throw new HttpException('无权限', HttpStatus.FORBIDDEN)
    const user = await this.userModel.findById(targetUserId).exec()
    if (!user) throw new HttpException('用户不存在', HttpStatus.NOT_FOUND)
    const expireAt = new Date()
    expireAt.setDate(expireAt.getDate() + 30)
    user.plan = 'vip'
    user.vipExpireAt = expireAt
    user.remaining = 999
    await user.save()
    return { success: true, plan: 'vip', expireAt }
  }

  @UseGuards(JwtAuthGuard)
  @Get('admins')
  async getAdmins(@CurrentUser('userId') adminUserId: string) {
    const admin = await this.userModel.findById(adminUserId).exec()
    if (admin?.role !== 'admin') throw new HttpException('无权限', HttpStatus.FORBIDDEN)
    const admins = await this.userModel.find({ role: 'admin' }).select('phone nickname email createdAt isSystemAdmin').lean().exec()
    return { admins }
  }

  @UseGuards(JwtAuthGuard)
  @Post('set-admin')
  async setAdmin(@Body('userId') targetUserId: string, @CurrentUser('userId') adminUserId: string) {
    const admin = await this.userModel.findById(adminUserId).exec()
    if (admin?.role !== 'admin') throw new HttpException('无权限', HttpStatus.FORBIDDEN)
    const user = await this.userModel.findById(targetUserId).exec()
    if (!user) throw new HttpException('用户不存在', HttpStatus.NOT_FOUND)
    if (user.role === 'admin') throw new HttpException('该用户已是管理员', HttpStatus.BAD_REQUEST)
    user.role = 'admin'
    await user.save()
    return { success: true, message: '已设为管理员' }
  }

  // ─── 订单管理 ──────────────

  @UseGuards(JwtAuthGuard)
  @Get('orders')
  async getOrders(@Query('page') page = '1', @Query('limit') limit = '20', @Query('status') status: string, @CurrentUser('userId') adminUserId: string) {
    const admin = await this.userModel.findById(adminUserId).exec()
    if (admin?.role !== 'admin') throw new HttpException('无权限', HttpStatus.FORBIDDEN)
    const filter: any = {}
    if (status) filter.status = status
    const skip = (Math.max(1, +page) - 1) * +limit
    const [orders, total] = await Promise.all([
      this.orderModel.find(filter).sort({ createdAt: -1 }).skip(skip).limit(+limit).lean().exec(),
      this.orderModel.countDocuments(filter).exec(),
    ])
    return { orders, total, page: +page }
  }

  @UseGuards(JwtAuthGuard)
  @Post('order/sync')
  async syncOrder(@Body('outTradeNo') outTradeNo: string, @CurrentUser('userId') adminUserId: string) {
    const admin = await this.userModel.findById(adminUserId).exec()
    if (admin?.role !== 'admin') throw new HttpException('无权限', HttpStatus.FORBIDDEN)
    const wxResult = await this.wechatPay.queryOrder(outTradeNo)
    const tradeState = wxResult?.trade_state
    const order = await this.orderModel.findOne({ outTradeNo }).exec()
    if (!order) throw new HttpException('订单不存在', HttpStatus.NOT_FOUND)
    if (tradeState === 'SUCCESS' && order.status === 'pending') {
      order.status = 'success'
      order.wxTransactionId = wxResult.transaction_id
      order.paidAt = new Date()
      await order.save()
      const user = await this.userModel.findById(order.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 { order, wxResult }
  }

  // ─── 系统配置（支持管理后台编辑） ──────

  @UseGuards(JwtAuthGuard)
  @Get('config')
  async getConfig(@CurrentUser('userId') adminUserId: string) {
    const admin = await this.userModel.findById(adminUserId).exec()
    if (admin?.role !== 'admin') throw new HttpException('无权限', HttpStatus.FORBIDDEN)
    // 从数据库读，不存在则返回默认值
    const cfg = await this.configModel.findOne({ key: 'site_config' }).exec()
    if (cfg) return cfg.value
    return DEFAULT_CONFIG
  }

  @UseGuards(JwtAuthGuard)
  @Post('config/save')
  async saveConfig(@Body() body: any, @CurrentUser('userId') adminUserId: string) {
    const admin = await this.userModel.findById(adminUserId).exec()
    if (admin?.role !== 'admin') throw new HttpException('无权限', HttpStatus.FORBIDDEN)
    await this.configModel.findOneAndUpdate(
      { key: 'site_config' },
      { key: 'site_config', value: body, description: '站点配置' },
      { upsert: true },
    ).exec()
    return { success: true }
  }

  // ─── 每日一题管理 ──────────────

  @UseGuards(JwtAuthGuard)
  @Get('questions')
  async getQuestions(@CurrentUser('userId') adminUserId: string) {
    const admin = await this.userModel.findById(adminUserId).exec()
    if (admin?.role !== 'admin') throw new HttpException('无权限', HttpStatus.FORBIDDEN)
    const cfg = await this.configModel.findOne({ key: 'daily_questions' }).exec()
    return cfg?.value || DEFAULT_QUESTIONS
  }

  @UseGuards(JwtAuthGuard)
  @Post('questions/save')
  async saveQuestions(@Body() body: any, @CurrentUser('userId') adminUserId: string) {
    const admin = await this.userModel.findById(adminUserId).exec()
    if (admin?.role !== 'admin') throw new HttpException('无权限', HttpStatus.FORBIDDEN)
    await this.configModel.findOneAndUpdate(
      { key: 'daily_questions' },
      { key: 'daily_questions', value: body, description: '每日一题题库' },
      { upsert: true },
    ).exec()
    return { success: true }
  }
}

const DEFAULT_CONFIG = {
  interview: { maxRoundsFree: 5, maxRoundsVip: 10, dailyFreeLimit: 3 },
  diagnosis: { dailyFreeLimit: 2 },
  optimize: { dailyFreeLimit: 2 },
  price: { monthly: 1990 },
  plans: {
    free: { name: '免费版', price: 0, features: ['每日 3 次 AI 模拟面试', '每场最多 5 轮 AI 对话', '基础面试报告', '简历诊断', '简历优化'] },
    growth: { name: '成长版', price: 1990, features: ['免费版全部权益', '无限面试次数', '每场最多 10 轮 AI 对话', '详细面试报告（四维评分）', '进步轨迹雷达图 + 打卡', '参考回答思路', '公司真题库'] },
  },
}

const DEFAULT_QUESTIONS = [
  { position: '通用', category: 'behavioral', question: '请做一个简单的自我介绍，突出你的核心优势和职业目标。', referenceAnswer: '建议结构：1) 基本信息 2) 教育背景与专业方向 3) 实习/项目经历 4) 核心优势 5) 职业目标' },
  { position: '前端工程师', category: 'technical', question: '请用 JavaScript 实现一个深拷贝函数，并说明可能存在的问题。', referenceAnswer: '可使用递归遍历，注意循环引用用 WeakMap 处理，特殊类型如 Date/RegExp/Map/Set 需单独处理。' },
  { position: '后端工程师', category: 'technical', question: '请说说你对 RESTful API 设计的理解，以及和 GraphQL 的区别。', referenceAnswer: 'RESTful 以资源为核心，使用 HTTP 方法操作；GraphQL 客户端可指定返回字段，减少过度获取。' },
  { position: 'AI 算法工程师', category: 'technical', question: '解释一下 Transformer 架构中的 Self-Attention 机制是如何工作的。', referenceAnswer: 'Self-Attention 通过 QKV 计算注意力权重，公式为 Attention(Q,K,V)=softmax(QK^T/√d)V。' },
]
