import {
  Controller,
  Get,
  Post,
  Put,
  Delete,
  Body,
  Param,
  UseGuards,
} from '@nestjs/common';
import { ApiTags, ApiBearerAuth, ApiOperation } from '@nestjs/swagger';
import { KitsService } from './kits.service';
import { CreateKitsConfigDto } from './dto/create-kits-config.dto';
import { UpdateKitsConfigDto } from './dto/update-kits-config.dto';
import { ImportKitsConfigDto } from './dto/import-kits-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('kits')
@ApiBearerAuth()
@Controller('kits')
@UseGuards(JwtAuthGuard, PermissionsGuard)
export class KitsController {
  constructor(private readonly kitsService: KitsService) {}

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

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

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

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

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

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

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