import {
  Controller,
  Get,
  Post,
  Body,
  Patch,
  Param,
  Delete,
  UseGuards,
  Request,
  ParseIntPipe,
  Query,
} from '@nestjs/common';
import { HomeworkReviewRulesService } from './review-rules.service';
import { CreateHomeworkReviewRuleDto } from './dto/create-review-rule.dto';
import { UpdateHomeworkReviewRuleDto } 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('homework/review-rules')
@UseGuards(JwtAuthGuard)
export class HomeworkReviewRulesController {
  constructor(private readonly reviewRulesService: HomeworkReviewRulesService) {}

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

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

  /**
   * 创建评审规则
   */
  @Post()
  @RequirePermission('homework:update')
  create(
    @Body() createDto: CreateHomeworkReviewRuleDto,
    @CurrentTenantId() tenantId: number,
    @Request() req?,
  ) {
    const creatorId = req?.user?.id;
    return this.reviewRulesService.create(createDto, tenantId, creatorId);
  }

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

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

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