import { Body, Controller, Delete, Get, Param, Patch, Post, UseGuards } from '@nestjs/common';
import { ApiBearerAuth, ApiSecurity, ApiTags } from '@nestjs/swagger';
import { Roles } from '../auth/decorators/roles.decorator';
import { RequireScopes } from '../auth/decorators/scopes.decorator';
import { UserOrApiKeyGuard } from '../auth/guards/auth.guard';
import { OrgRolesGuard } from '../auth/guards/org-roles.guard';
import { ScopesGuard } from '../auth/guards/scopes.guard';
import { DevicesService } from './devices.service';
import { CreateDeviceDto, UpdateDeviceDto } from './dto/devices.dto';

@ApiTags('devices')
@ApiBearerAuth('jwt')
@ApiSecurity('apiKey')
@Controller('orgs/:orgId/devices')
@UseGuards(UserOrApiKeyGuard, OrgRolesGuard, ScopesGuard)
export class DevicesController {
  constructor(private readonly devicesService: DevicesService) {}

  @Get()
  @RequireScopes('devices:read')
  list(@Param('orgId') orgId: string) {
    return this.devicesService.list(orgId);
  }

  @Post()
  @Roles('ORG_ADMIN')
  @RequireScopes('devices:read') // API keys cannot create devices; role gate handles users
  create(@Param('orgId') orgId: string, @Body() dto: CreateDeviceDto) {
    return this.devicesService.create(orgId, dto);
  }

  @Get(':deviceId/location')
  @RequireScopes('devices:read')
  getLocation(@Param('orgId') orgId: string, @Param('deviceId') deviceId: string) {
    return this.devicesService.getLocation(orgId, deviceId);
  }

  @Patch(':deviceId')
  @Roles('ORG_ADMIN')
  update(
    @Param('orgId') orgId: string,
    @Param('deviceId') deviceId: string,
    @Body() dto: UpdateDeviceDto,
  ) {
    return this.devicesService.update(orgId, deviceId, dto);
  }

  @Delete(':deviceId')
  @Roles('ORG_ADMIN')
  remove(@Param('orgId') orgId: string, @Param('deviceId') deviceId: string) {
    return this.devicesService.remove(orgId, deviceId);
  }
}
