import {
  Controller,
  Get,
  Post,
  Put,
  Delete,
  Body,
  Param,
  UseGuards,
} from '@nestjs/common';
import { ApiTags, ApiBearerAuth, ApiOperation } from '@nestjs/swagger';
import { GatherService } from './gather.service';
import { CreateGatherConfigDto } from './dto/create-gather-config.dto';
import { UpdateGatherConfigDto } from './dto/update-gather-config.dto';
import { ImportGatherConfigDto } from './dto/import-gather-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('gather')
@ApiBearerAuth()
@Controller('gather')
@UseGuards(JwtAuthGuard, PermissionsGuard)
export class GatherController {
  constructor(private readonly gatherService: GatherService) {}

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

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

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

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

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

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

  @Post('import-from-server')
  @RequirePermission('gather.manage')
  @ApiOperation({ summary: 'Import GatherManager.json from server' })
  importFromServer(@CurrentTenant() licenseId: string, @Body() dto: ImportGatherConfigDto) {
    return this.gatherService.importFromServer(licenseId, dto.config_name, dto.description);
  }
}
