import {
  Controller,
  Get,
  Post,
  Body,
  Patch,
  Param,
  Delete,
  UseGuards,
  Request,
  ParseIntPipe,
  Query,
} from '@nestjs/common';
import { ReviewRulesService } from './review-rules.service';
import { CreateReviewRuleDto } from './dto/create-review-rule.dto';
import { UpdateReviewRuleDto } from './dto/update-review-rule.dto';
import { JwtAuthGuard } from '../../auth/guards/jwt-auth.guard';
import { RequirePermission } from '../../auth/decorators/require-permission.decorator';
import { CurrentTenantId } from '../../auth/decorators/current-tenant-id.decorator';

@Controller('contests/review-rules')
@UseGuards(JwtAuthGuard)
export class ReviewRulesController {
  constructor(private readonly reviewRulesService: ReviewRulesService) {}

  /**
   * 分页查询评审规则列表
   */
  @Get()
  @RequirePermission('contest:read')
  findAll(
    @Query('page') page?: string,
    @Query('pageSize') pageSize?: string,
    @Query('ruleName') ruleName?: string,
    @CurrentTenantId() tenantId?: number,
  ) {
    return this.reviewRulesService.findAll(
      tenantId,
      page ? parseInt(page) : 1,
      pageSize ? parseInt(pageSize) : 10,
      ruleName,
    );
  }

  /**
   * 获取所有可用的评审规则（用于活动创建时选择）
   */
  @Get('select')
  @RequirePermission('contest:read')
  findAllForSelect(@CurrentTenantId() tenantId?: number) {
    return this.reviewRulesService.findAllForSelect(tenantId);
  }

  /**
   * 创建评审规则（独立创建，不关联活动）
   */
  @Post()
  @RequirePermission('contest:update')
  create(
    @Body() createReviewRuleDto: CreateReviewRuleDto,
    @CurrentTenantId() tenantId?: number,
    @Request() req?,
  ) {
    const creatorId = req?.user?.id;
    return this.reviewRulesService.create(createReviewRuleDto, tenantId, creatorId);
  }

  /**
   * 根据ID查找评审规则
   */
  @Get(':id')
  @RequirePermission('contest:read')
  findById(
    @Param('id', ParseIntPipe) id: number,
    @CurrentTenantId() tenantId?: number,
  ) {
    return this.reviewRulesService.findById(id, tenantId);
  }

  /**
   * 更新评审规则
   */
  @Patch(':id')
  @RequirePermission('contest:update')
  update(
    @Param('id', ParseIntPipe) id: number,
    @Body() updateReviewRuleDto: UpdateReviewRuleDto,
    @CurrentTenantId() tenantId?: number,
    @Request() req?,
  ) {
    const modifierId = req?.user?.id;
    return this.reviewRulesService.update(id, updateReviewRuleDto, tenantId, modifierId);
  }

  /**
   * 删除评审规则（软删除）
   */
  @Delete(':id')
  @RequirePermission('contest:update')
  remove(
    @Param('id', ParseIntPipe) id: number,
    @CurrentTenantId() tenantId?: number,
  ) {
    return this.reviewRulesService.remove(id, tenantId);
  }
}

