import {
  Controller,
  Get,
  Post,
  Body,
  Patch,
  Param,
  Delete,
  Query,
  UseGuards,
  Request,
} from '@nestjs/common';
import { StudentsService } from './students.service';
import { CreateStudentDto } from './dto/create-student.dto';
import { UpdateStudentDto } from './dto/update-student.dto';
import { JwtAuthGuard } from '../../auth/guards/jwt-auth.guard';

@Controller('students')
@UseGuards(JwtAuthGuard)
export class StudentsController {
  constructor(private readonly studentsService: StudentsService) {}

  @Post()
  create(@Body() createStudentDto: CreateStudentDto, @Request() req) {
    const tenantId = req.tenantId || req.user?.tenantId;
    if (!tenantId) {
      throw new Error('无法确定租户信息');
    }
    const creatorId = req.user?.id;
    return this.studentsService.create(createStudentDto, tenantId, creatorId);
  }

  @Get()
  findAll(
    @Query('page') page?: string,
    @Query('pageSize') pageSize?: string,
    @Query('classId') classId?: string,
    @Request() req?: any,
  ) {
    const tenantId = req?.tenantId || req?.user?.tenantId;
    return this.studentsService.findAll(
      page ? parseInt(page) : 1,
      pageSize ? parseInt(pageSize) : 10,
      tenantId,
      classId ? parseInt(classId) : undefined,
    );
  }

  @Get('user/:userId')
  findByUserId(@Param('userId') userId: string, @Request() req) {
    const tenantId = req.tenantId || req.user?.tenantId;
    return this.studentsService.findByUserId(+userId, tenantId);
  }

  @Get(':id')
  findOne(@Param('id') id: string, @Request() req) {
    const tenantId = req.tenantId || req.user?.tenantId;
    return this.studentsService.findOne(+id, tenantId);
  }

  @Patch(':id')
  update(
    @Param('id') id: string,
    @Body() updateStudentDto: UpdateStudentDto,
    @Request() req,
  ) {
    const tenantId = req.tenantId || req.user?.tenantId;
    const modifierId = req.user?.id;
    return this.studentsService.update(+id, updateStudentDto, tenantId, modifierId);
  }

  @Delete(':id')
  remove(@Param('id') id: string, @Request() req) {
    const tenantId = req.tenantId || req.user?.tenantId;
    return this.studentsService.remove(+id, tenantId);
  }
}

