import {
  Controller,
  Get,
  Post,
  Body,
  Patch,
  Param,
  Delete,
  UseGuards,
  Request,
  Query,
  ParseIntPipe,
} from '@nestjs/common';
import { TenantsService } from './tenants.service';
import { CreateTenantDto } from './dto/create-tenant.dto';
import { UpdateTenantDto } from './dto/update-tenant.dto';
import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard';
import { PermissionsGuard } from '../auth/guards/permissions.guard';
import { RequirePermission } from '../auth/decorators/require-permission.decorator';

@Controller('tenants')
@UseGuards(JwtAuthGuard, PermissionsGuard)
export class TenantsController {
  constructor(private readonly tenantsService: TenantsService) {}

  @Post()
  @RequirePermission('tenant:create')
  create(@Body() createTenantDto: CreateTenantDto, @Request() req) {
    const userId = req.user?.userId;
    const currentTenantId = req.user?.tenantId;
    return this.tenantsService.create(createTenantDto, userId, currentTenantId);
  }

  @Get()
  @RequirePermission('tenant:read')
  findAll(
    @Query('page', new ParseIntPipe({ optional: true })) page: number = 1,
    @Query('pageSize', new ParseIntPipe({ optional: true }))
    pageSize: number = 10,
  ) {
    return this.tenantsService.findAll(page, pageSize);
  }

  @Get(':id')
  @RequirePermission('tenant:read')
  findOne(@Param('id', ParseIntPipe) id: number) {
    return this.tenantsService.findOne(id);
  }

  @Patch(':id')
  @RequirePermission('tenant:update')
  update(
    @Param('id', ParseIntPipe) id: number,
    @Body() updateTenantDto: UpdateTenantDto,
    @Request() req,
  ) {
    const userId = req.user?.userId;
    const currentTenantId = req.user?.tenantId;
    return this.tenantsService.update(
      id,
      updateTenantDto,
      userId,
      currentTenantId,
    );
  }

  @Delete(':id')
  @RequirePermission('tenant:delete')
  remove(@Param('id', ParseIntPipe) id: number, @Request() req) {
    const currentTenantId = req.user?.tenantId;
    return this.tenantsService.remove(id, currentTenantId);
  }

  @Get(':id/menus')
  @RequirePermission('tenant:read')
  getTenantMenus(@Param('id', ParseIntPipe) id: number) {
    return this.tenantsService.getTenantMenus(id);
  }
}
