import {
  Controller,
  Get,
  Post,
  Put,
  Delete,
  Body,
  Param,
  UseGuards,
} from '@nestjs/common';
import { ApiTags, ApiBearerAuth, ApiOperation } from '@nestjs/swagger';
import { TeleportService } from './teleport.service';
import { CreateTeleportConfigDto } from './dto/create-teleport-config.dto';
import { UpdateTeleportConfigDto } from './dto/update-teleport-config.dto';
import { ImportTeleportConfigDto } from './dto/import-teleport-config.dto';
import { CurrentTenant } from '../../common/decorators/current-tenant.decorator';
import { RequirePermission } from '../../common/decorators/require-permission.decorator';
import { JwtAuthGuard } from '../../common/guards/jwt-auth.guard';
import { PermissionsGuard } from '../../common/guards/permissions.guard';

@ApiTags('teleport')
@ApiBearerAuth()
@Controller('teleport')
@UseGuards(JwtAuthGuard, PermissionsGuard)
export class TeleportController {
  constructor(private readonly teleportService: TeleportService) {}

  @Get('configs')
  @RequirePermission('teleport.view')
  @ApiOperation({ summary: 'List teleport configs (summaries)' })
  getConfigs(@CurrentTenant() licenseId: string) {
    return this.teleportService.getConfigs(licenseId);
  }

  @Get('configs/:id')
  @RequirePermission('teleport.view')
  @ApiOperation({ summary: 'Get full teleport config with data' })
  getConfig(@CurrentTenant() licenseId: string, @Param('id') id: string) {
    return this.teleportService.getConfig(licenseId, id);
  }

  @Post('configs')
  @RequirePermission('teleport.manage')
  @ApiOperation({ summary: 'Create teleport config' })
  createConfig(@CurrentTenant() licenseId: string, @Body() dto: CreateTeleportConfigDto) {
    return this.teleportService.createConfig(licenseId, dto);
  }

  @Put('configs/:id')
  @RequirePermission('teleport.manage')
  @ApiOperation({ summary: 'Update teleport config' })
  updateConfig(
    @CurrentTenant() licenseId: string,
    @Param('id') id: string,
    @Body() dto: UpdateTeleportConfigDto,
  ) {
    return this.teleportService.updateConfig(licenseId, id, dto);
  }

  @Delete('configs/:id')
  @RequirePermission('teleport.manage')
  @ApiOperation({ summary: 'Delete teleport config' })
  deleteConfig(@CurrentTenant() licenseId: string, @Param('id') id: string) {
    return this.teleportService.deleteConfig(licenseId, id);
  }

  @Post('configs/:id/apply')
  @RequirePermission('teleport.manage')
  @ApiOperation({ summary: 'Deploy teleport config to server' })
  applyToServer(@CurrentTenant() licenseId: string, @Param('id') id: string) {
    return this.teleportService.applyToServer(licenseId, id);
  }

  @Post('import-from-server')
  @RequirePermission('teleport.manage')
  @ApiOperation({ summary: 'Import NTeleportation.json from server via NATS' })
  importFromServer(@CurrentTenant() licenseId: string, @Body() dto: ImportTeleportConfigDto) {
    return this.teleportService.importFromServer(licenseId, dto.config_name, dto.description);
  }
}
