import {
  Controller,
  Get,
  Post,
  Put,
  Delete,
  Body,
  Param,
  UseGuards,
} from '@nestjs/common';
import { ApiTags, ApiBearerAuth, ApiOperation } from '@nestjs/swagger';
import { AutoDoorsService } from './autodoors.service';
import { CreateAutoDoorsConfigDto } from './dto/create-autodoors-config.dto';
import { UpdateAutoDoorsConfigDto } from './dto/update-autodoors-config.dto';
import { ImportAutoDoorsConfigDto } from './dto/import-autodoors-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('autodoors')
@ApiBearerAuth()
@Controller('autodoors')
@UseGuards(JwtAuthGuard, PermissionsGuard)
export class AutoDoorsController {
  constructor(private readonly autoDoorsService: AutoDoorsService) {}

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

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

  @Post('configs')
  @RequirePermission('autodoors.manage')
  @ApiOperation({ summary: 'Create AutoDoors config' })
  createConfig(@CurrentTenant() licenseId: string, @Body() dto: CreateAutoDoorsConfigDto) {
    return this.autoDoorsService.createConfig(licenseId, dto);
  }

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

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

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

  @Post('import-from-server')
  @RequirePermission('autodoors.manage')
  @ApiOperation({ summary: 'Import AutoDoors.json from server' })
  importFromServer(@CurrentTenant() licenseId: string, @Body() dto: ImportAutoDoorsConfigDto) {
    return this.autoDoorsService.importFromServer(licenseId, dto.config_name, dto.description);
  }
}
