import {
  Controller,
  Get,
  Post,
  Body,
  Patch,
  Param,
  Delete,
  Query,
  UseGuards,
  Request,
} from '@nestjs/common';
import { TeachersService } from './teachers.service';
import { CreateTeacherDto } from './dto/create-teacher.dto';
import { UpdateTeacherDto } from './dto/update-teacher.dto';
import { JwtAuthGuard } from '../../auth/guards/jwt-auth.guard';

@Controller('teachers')
@UseGuards(JwtAuthGuard)
export class TeachersController {
  constructor(private readonly teachersService: TeachersService) {}

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

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

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

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

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

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

