import { Controller, Post, Get, Body, Param, UseGuards } from '@nestjs/common'
import { InjectModel } from '@nestjs/mongoose'
import { Model } from 'mongoose'
import { JwtAuthGuard } from '../../common/guards/jwt-auth.guard'
import { CurrentUser } from '../../common/decorators/current-user.decorator'
import { Contribution, ContributionDocument } from '../schemas/contribution.schema'
import { CompanyBank, CompanyBankDocument } from '../schemas/company-bank.schema'

@Controller('contribution')
@UseGuards(JwtAuthGuard)
export class ContributionController {
  constructor(
    @InjectModel(Contribution.name) private contributionModel: Model<ContributionDocument>,
    @InjectModel(CompanyBank.name) private companyBankModel: Model<CompanyBankDocument>,
  ) {}

  @Post()
  async create(
    @CurrentUser('userId') userId: string,
    @Body() body: {
      interviewId: string
      company: string
      position: string
      rounds?: string
      questions?: string[]
      experience?: string
      tags?: string[]
    },
  ) {
    const contribution = await this.contributionModel.create({
      userId,
      interviewId: body.interviewId,
      company: body.company,
      position: body.position,
      rounds: body.rounds || '',
      questions: body.questions || [],
      experience: body.experience || '',
      tags: body.tags || [],
      verified: false,
    })

    // Update company bank
    if (body.questions && body.questions.length > 0) {
      let bank = await this.companyBankModel.findOne({
        company: body.company,
        position: body.position,
      }).exec()

      if (!bank) {
        bank = await this.companyBankModel.create({
          company: body.company,
          position: body.position,
          questions: [],
          contributionCount: 0,
          viewCount: 0,
        })
      }

      // Add new questions (avoid duplicates)
      for (const q of body.questions) {
        const exists = bank.questions.some(eq => eq.content === q)
        if (!exists) {
          bank.questions.push({
            content: q,
            type: 'general',
            referenceAnswer: '',
            difficulty: 'medium',
            frequency: 1,
            tags: body.tags || [],
          })
        } else {
          // Increment frequency
          const existing = bank.questions.find(eq => eq.content === q)
          if (existing) existing.frequency += 1
        }
      }
      bank.contributionCount += 1
      await bank.save()
    }

    return {
      id: (contribution as any)._id.toString(),
      company: contribution.company,
      position: contribution.position,
      message: '感谢你的分享！你的面经将帮助更多同学准备面试',
    }
  }

  @Get('company/:company/position/:position')
  async getBank(@Param('company') company: string, @Param('position') position: string) {
    const bank = await this.companyBankModel.findOne({ company, position }).exec()
    if (!bank) return { company, position, questions: [], contributionCount: 0 }

    bank.viewCount += 1
    await bank.save()

    return {
      company: bank.company,
      position: bank.position,
      questions: bank.questions.sort((a, b) => b.frequency - a.frequency),
      contributionCount: bank.contributionCount,
      viewCount: bank.viewCount,
    }
  }

  @Get('company/:company')
  async getCompanyBanks(@Param('company') company: string) {
    const banks = await this.companyBankModel.find({ company }).exec()
    return banks.map(b => ({
      position: b.position,
      questionCount: b.questions.length,
      contributionCount: b.contributionCount,
    }))
  }

  @Get('my')
  async getMyContributions(@CurrentUser('userId') userId: string) {
    return this.contributionModel
      .find({ userId })
      .sort({ createdAt: -1 })
      .select('company position rounds experience createdAt')
      .exec()
  }
}