import * as crypto from 'crypto'
import { Injectable, HttpException, HttpStatus } from '@nestjs/common'
import { InjectModel } from '@nestjs/mongoose'
import { Model } from 'mongoose'
import { Resume, ResumeDocument } from './resume.schema'

@Injectable()
export class ResumeService {
  constructor(@InjectModel(Resume.name) private resumeModel: Model<ResumeDocument>) {}

  async create(userId: string, title: string, content: string, targetPosition?: string) {
    const contentHash = crypto.createHash('md5').update(content).digest('hex')
    const resume = await this.resumeModel.create({ userId, title, content, targetPosition, contentHash, version: 1 })
    return resume.toObject()
  }

  async list(userId: string) {
    const list = await this.resumeModel.find({ userId }).sort({ createdAt: -1 }).exec()
    return list.map(r => ({
      id: r._id.toString(),
      title: r.title,
      targetPosition: r.targetPosition,
      version: r.version,
      contentHash: r.contentHash,
      paidDownload: r.paidDownload,
      createdAt: r.createdAt,
    }))
  }

  async getDetail(resumeId: string, userId: string) {
    const resume = await this.resumeModel.findOne({ _id: resumeId, userId }).exec()
    if (!resume) throw new HttpException('简历不存在', HttpStatus.NOT_FOUND)
    return resume.toObject()
  }

  /** AI 优化后更新内容，若内容变化则新建版本 */
  async updateAfterOptimize(resumeId: string, userId: string, newContent: string, targetPosition?: string) {
    const resume = await this.resumeModel.findOne({ _id: resumeId, userId }).exec()
    if (!resume) throw new HttpException('简历不存在', HttpStatus.NOT_FOUND)

    const newHash = crypto.createHash('md5').update(newContent).digest('hex')
    if (newHash === resume.contentHash) return resume.toObject()

    // Same user, increment version as new record
    const created = await this.resumeModel.create({
      userId,
      title: resume.title,
      content: newContent,
      targetPosition: targetPosition || resume.targetPosition,
      contentHash: newHash,
      version: (resume.version || 1) + 1,
    })
    return created.toObject()
  }

  async markPaid(resumeId: string, userId: string) {
    await this.resumeModel.updateOne({ _id: resumeId, userId }, { paidDownload: true }).exec()
  }

  async delete(resumeId: string, userId: string) {
    const res = await this.resumeModel.deleteOne({ _id: resumeId, userId }).exec()
    if (res.deletedCount === 0) throw new HttpException('简历不存在', HttpStatus.NOT_FOUND)
    return { message: '删除成功' }
  }
}
