import {
  Controller,
  Get,
  Post,
  Body,
  Param,
  Delete,
  Query,
  UseGuards,
  Request,
  ParseIntPipe,
} from '@nestjs/common';
import { WorksService } from './works.service';
import { SubmitWorkDto } from './dto/submit-work.dto';
import { QueryWorkDto } from './dto/query-work.dto';
import { QueryGuidedWorkDto } from './dto/query-guided-work.dto';
import { JwtAuthGuard } from '../../auth/guards/jwt-auth.guard';
import { RequirePermission } from '../../auth/decorators/require-permission.decorator';

@Controller('contests/works')
@UseGuards(JwtAuthGuard)
export class WorksController {
  constructor(private readonly worksService: WorksService) {}

  @Post('submit')
  @RequirePermission('work:submit')
  submit(@Body() submitWorkDto: SubmitWorkDto, @Request() req) {
    const tenantId = req.tenantId || req.user?.tenantId;
    if (!tenantId) {
      throw new Error('无法确定租户信息');
    }
    const submitterUserId = req.user?.userId;
    if (!submitterUserId) {
      throw new Error('无法确定提交人信息');
    }
    return this.worksService.submit(submitWorkDto, tenantId, submitterUserId);
  }

  @Get('stats')
  @RequirePermission('work:read')
  getStats(@Query('contestId') contestId?: string) {
    return this.worksService.getStats(contestId ? parseInt(contestId) : undefined);
  }

  @Get()
  @RequirePermission('work:read')
  findAll(@Query() queryDto: QueryWorkDto, @Request() req) {
    const tenantId = req.tenantId || req.user?.tenantId;
    return this.worksService.findAll(queryDto, tenantId);
  }

  /**
   * 获取教师指导的作品列表
   */
  @Get('guided')
  @RequirePermission('activity:read')
  findGuidedWorks(
    @Query() queryDto: QueryGuidedWorkDto,
    @Request() req,
  ) {
    const tenantId = req.tenantId || req.user?.tenantId;
    const teacherUserId = req.user?.userId;
    if (!teacherUserId) {
      throw new Error('无法确定教师信息');
    }
    return this.worksService.findGuidedWorks(queryDto, tenantId, teacherUserId);
  }

  @Get(':id')
  @RequirePermission('work:read')
  findOne(@Param('id', ParseIntPipe) id: number, @Request() req) {
    const tenantId = req.tenantId || req.user?.tenantId;
    return this.worksService.findOne(id, tenantId);
  }

  @Get('registration/:registrationId/versions')
  @RequirePermission('work:read')
  getVersions(
    @Param('registrationId', ParseIntPipe) registrationId: number,
    @Request() req,
  ) {
    const tenantId = req.tenantId || req.user?.tenantId;
    return this.worksService.getVersions(registrationId, tenantId);
  }

  @Delete(':id')
  @RequirePermission('work:update')
  remove(@Param('id', ParseIntPipe) id: number, @Request() req) {
    const tenantId = req.tenantId || req.user?.tenantId;
    return this.worksService.remove(id, tenantId);
  }
}
