import {
  Controller,
  Get,
  Post,
  Body,
  Param,
  UseGuards,
  ParseIntPipe,
  Query,
  Request,
} from '@nestjs/common';
import { SubmissionsService } from './submissions.service';
import { QuerySubmissionDto } from './dto/query-submission.dto';
import { CreateSubmissionDto } from './dto/create-submission.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/submissions')
@UseGuards(JwtAuthGuard)
export class SubmissionsController {
  constructor(private readonly submissionsService: SubmissionsService) {}

  /**
   * 分页查询提交记录列表
   */
  @Get()
  @RequirePermission('homework:read')
  findAll(
    @Query() queryDto: QuerySubmissionDto,
    @CurrentTenantId() tenantId?: number,
  ) {
    return this.submissionsService.findAll(queryDto, tenantId);
  }

  /**
   * 获取班级树结构（用于左侧筛选）
   */
  @Get('class-tree')
  @RequirePermission('homework:read')
  getClassTree(@CurrentTenantId() tenantId: number) {
    return this.submissionsService.getClassTree(tenantId);
  }

  /**
   * 获取当前用户对某作业的提交记录
   */
  @Get('my/:homeworkId')
  @RequirePermission('homework:read', 'homework:student:read')
  getMySubmission(
    @Param('homeworkId', ParseIntPipe) homeworkId: number,
    @Request() req: any,
    @CurrentTenantId() tenantId: number,
  ) {
    return this.submissionsService.findByStudentAndHomework(
      req.user.userId,
      homeworkId,
      tenantId,
    );
  }

  /**
   * 学生提交作业
   */
  @Post()
  @RequirePermission('homework:read', 'homework:student:read')
  submit(
    @Body() createDto: CreateSubmissionDto,
    @Request() req: any,
    @CurrentTenantId() tenantId: number,
  ) {
    return this.submissionsService.create(createDto, req.user.userId, tenantId);
  }

  /**
   * 根据ID查找提交记录详情
   */
  @Get(':id')
  @RequirePermission('homework:read')
  findById(
    @Param('id', ParseIntPipe) id: number,
    @CurrentTenantId() tenantId?: number,
  ) {
    return this.submissionsService.findById(id, tenantId);
  }
}
