import { Injectable } from '@nestjs/common'
import { InjectModel } from '@nestjs/mongoose'
import { Model } from 'mongoose'
import { Feedback } from './feedback.schema'

@Injectable()
export class FeedbackService {
  constructor(@InjectModel(Feedback.name) private model: Model<Feedback>) {}

  async create(data: { userId: string; type: string; content: string; contact?: string }) {
    return this.model.create(data)
  }

  async findAll(page = 1, limit = 20) {
    const skip = (page - 1) * limit
    const items = await this.model.find().sort({ createdAt: -1 }).skip(skip).limit(limit).lean()
    let populated: any[] = items
    try {
      populated = await this.model.populate(items, { path: 'userId', select: 'nickname phone email' })
    } catch {}
    const total = await this.model.countDocuments()
    return { items: populated, total, page, limit }
  }

  async markResolved(id: string) {
    return this.model.findByIdAndUpdate(id, { status: 'resolved' }, { new: true })
  }
}
