import {
  Controller,
  Get,
  Post,
  Body,
  Patch,
  Param,
  Delete,
  Query,
  UseGuards,
  Request,
} from '@nestjs/common';
import { UsersService } from './users.service';
import { CreateUserDto } from './dto/create-user.dto';
import { UpdateUserDto } from './dto/update-user.dto';
import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard';
import { TenantId } from '../tenants/decorators/tenant.decorator';

@Controller('users')
@UseGuards(JwtAuthGuard)
export class UsersController {
  constructor(private readonly usersService: UsersService) {}

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

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

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

  @Patch(':id')
  update(
    @Param('id') id: string,
    @Body() updateUserDto: UpdateUserDto,
    @Request() req,
  ) {
    const tenantId = req.tenantId || req.user?.tenantId;
    return this.usersService.update(+id, updateUserDto, tenantId);
  }

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