import {
  Controller,
  Get,
  Post,
  Body,
  Patch,
  Param,
  Delete,
  Query,
  UseGuards,
  Request,
} from '@nestjs/common';
import { ClassesService } from './classes.service';
import { CreateClassDto } from './dto/create-class.dto';
import { UpdateClassDto } from './dto/update-class.dto';
import { JwtAuthGuard } from '../../auth/guards/jwt-auth.guard';

@Controller('classes')
@UseGuards(JwtAuthGuard)
export class ClassesController {
  constructor(private readonly classesService: ClassesService) {}

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

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

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

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

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

