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);
  }

  /**
   * 用户统计（仅超管）
   * 注意：此路由必须在 :id 路由之前，否则 'stats' 会被当作 id 解析
   */
  @Get('stats')
  async getStats(@Request() req) {
    return this.usersService.getStats();
  }

  @Get()
  findAll(
    @Query('page') page?: string,
    @Query('pageSize') pageSize?: string,
    @Query('keyword') keyword?: string,
    @Query('userType') userType?: string,
    @Query('filterTenantId') filterTenantId?: string,
    @Query('userSource') userSource?: string,
    @Query('status') status?: string,
    @Request() req?: any,
  ) {
    const tenantId = req?.tenantId || req?.user?.tenantId;

    // 判断是否超级租户
    const isSuperTenant = req?.user?.isSuperTenant === true;

    return this.usersService.findAll({
      page: page ? parseInt(page) : 1,
      pageSize: pageSize ? parseInt(pageSize) : 10,
      tenantId,
      keyword,
      isSuperTenant,
      userType,
      filterTenantId: filterTenantId ? parseInt(filterTenantId) : undefined,
      userSource,
      status,
    });
  }

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

  @Patch(':id/status')
  updateStatus(
    @Param('id') id: string,
    @Body('status') status: 'enabled' | 'disabled',
    @Request() req,
  ) {
    const operatorId = req.user?.userId || req.user?.id;
    return this.usersService.updateStatus(+id, status, operatorId);
  }

  @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);
  }
}
