import { Injectable, Logger } from '@nestjs/common'
import { Cron } from '@nestjs/schedule'
import { InjectModel } from '@nestjs/mongoose'
import { Model } from 'mongoose'
import { WechatTokenService } from './wechat-token.service'
import { DailyQuestion, DailyQuestionDocument } from '../schemas/daily-question.schema'
import { User, UserDocument } from '../user/user.schema'

const DAILY_QUESTION_TEMPLATE_ID = process.env.WX_DAILY_QUESTION_TMPL || ''

@Injectable()
export class DailyQuestionPushService {
  private readonly logger = new Logger(DailyQuestionPushService.name)

  constructor(
    @InjectModel(DailyQuestion.name) private dailyQuestionModel: Model<DailyQuestionDocument>,
    @InjectModel(User.name) private userModel: Model<UserDocument>,
    private wechatToken: WechatTokenService,
  ) {}

  @Cron('0 8 * * *')
  async pushDailyQuestion() {
    this.logger.log('开始每日一题推送任务')

    if (!DAILY_QUESTION_TEMPLATE_ID) {
      this.logger.warn('未配置 WX_DAILY_QUESTION_TMPL，跳过每日推送')
      return
    }

    const today = new Date()
    today.setHours(0, 0, 0, 0)

    const question = await this.dailyQuestionModel.findOne({ pushed: false }).sort({ date: -1 }).exec()
    if (!question) {
      this.logger.warn('没有未推送的题目')
      return
    }

    const users = await this.userModel.find({ wxOpenid: { $ne: '', $exists: true } }).exec()
    this.logger.log(`找到 ${users.length} 个用户待推送`)

    let successCount = 0
    for (const user of users) {
      if (!user.wxOpenid) continue
      const ok = await this.wechatToken.sendSubscribeMessage(
        user.wxOpenid,
        DAILY_QUESTION_TEMPLATE_ID,
        {
          thing1: { value: question.question.slice(0, 20) + (question.question.length > 20 ? '...' : '') },
          thing2: { value: question.position || '通用' },
          thing3: { value: question.referenceAnswer.slice(0, 20) + (question.referenceAnswer.length > 20 ? '...' : '') },
        },
        'pages/interview/interview',
      )
      if (ok) successCount++
    }

    question.pushed = true
    await question.save()

    this.logger.log(`每日一题推送完成：成功 ${successCount}/${users.length}`)
  }
}
