import { Controller, Get, Body, Post, Delete, Param, UseGuards, HttpException, HttpStatus } from '@nestjs/common'
import { InjectModel } from '@nestjs/mongoose'
import { Model } from 'mongoose'
import { HotPosition, HotPositionDocument } from './positions.schema'
import { JwtAuthGuard } from '../../common/guards/jwt-auth.guard'
import { Public } from '../../common/decorators/public.decorator'
import { CurrentUser } from '../../common/decorators/current-user.decorator'
import { User, UserDocument } from '../user/user.schema'

@Controller('positions')
export class PositionsController {
  constructor(
    @InjectModel(HotPosition.name) private positionModel: Model<HotPositionDocument>,
    @InjectModel(User.name) private userModel: Model<UserDocument>,
  ) {}

  @Public()
  @Get('hot')
  async hot() {
    return this.positionModel.find({ active: true }).sort({ sort: 1 }).lean().exec()
  }

  // ─── 管理后台 CRUD ──────────────────────

  @UseGuards(JwtAuthGuard)
  @Post('admin/list')
  async adminList(@CurrentUser('userId') adminUserId: string) {
    const admin = await this.userModel.findById(adminUserId).exec()
    if (admin?.role !== 'admin') throw new HttpException('无权限', HttpStatus.FORBIDDEN)
    return this.positionModel.find().sort({ sort: 1 }).lean().exec()
  }

  @UseGuards(JwtAuthGuard)
  @Post('admin/save')
  async save(@Body() body: HotPosition & { _id?: string }, @CurrentUser('userId') adminUserId: string) {
    const admin = await this.userModel.findById(adminUserId).exec()
    if (admin?.role !== 'admin') throw new HttpException('无权限', HttpStatus.FORBIDDEN)
    if (body._id) {
      await this.positionModel.findByIdAndUpdate(body._id, body).exec()
      return { success: true }
    }
    const created = await this.positionModel.create(body)
    return { success: true, id: created._id }
  }

  @UseGuards(JwtAuthGuard)
  @Delete('admin/:id')
  async remove(@Param('id') id: string, @CurrentUser('userId') adminUserId: string) {
    const admin = await this.userModel.findById(adminUserId).exec()
    if (admin?.role !== 'admin') throw new HttpException('无权限', HttpStatus.FORBIDDEN)
    await this.positionModel.findByIdAndDelete(id).exec()
    return { success: true }
  }
}
