import {
  Controller,
  Get,
  Post,
  Body,
  Patch,
  Param,
  Delete,
  Query,
  UseGuards,
  Request,
} from '@nestjs/common';
import { PermissionsService } from './permissions.service';
import { CreatePermissionDto } from './dto/create-permission.dto';
import { UpdatePermissionDto } from './dto/update-permission.dto';
import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard';
import { Roles } from '../auth/decorators/roles.decorator';

@Controller('permissions')
@UseGuards(JwtAuthGuard)
export class PermissionsController {
  constructor(private readonly permissionsService: PermissionsService) {}

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

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

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

  @Patch(':id')
  @Roles('super_admin')
  update(
    @Param('id') id: string,
    @Body() updatePermissionDto: UpdatePermissionDto,
    @Request() req,
  ) {
    const tenantId = req.tenantId || req.user?.tenantId;
    return this.permissionsService.update(+id, updatePermissionDto, tenantId);
  }

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