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 resume = await this.resumeModel.create({ userId, title, content, targetPosition })
    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,
      createdAt: (r as any).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()
  }

  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: '删除成功' }
  }
}
