import { Body, Controller, Get, Post, Query } from '@nestjs/common';
import { ApiBody, ApiOperation, ApiQuery, ApiResponse, ApiTags } from '@nestjs/swagger';
import { UserRole } from '@prisma/client';
import { CurrentUser } from '../common/current-user.decorator';
import { RequireRole } from '../auth/require-role.decorator';
import { RequestUser } from '../common/request-user';
import { FeatureKey } from '../features/feature-catalog';
import { RequireFeature } from '../features/require-feature.decorator';
import { ApiProtectedEndpoint, ApiValidationError, ESTATE_ID_EXAMPLE, GUARD_ID_EXAMPLE, USER_ID_EXAMPLE } from '../common/swagger-docs';
import { CreateGuardDto } from './dto/create-guard.dto';
import { GuardsService } from './guards.service';

@ApiTags('Guards')
@ApiProtectedEndpoint()
@Controller({ path: 'guards', version: '1' })
export class GuardsController {
  constructor(private readonly guardsService: GuardsService) {}

  @Get()
  @RequireRole(UserRole.ESTATE_ADMIN, UserRole.SECURITY_SUPERVISOR)
  @RequireFeature(FeatureKey.GUARDS_VIEW)
  @ApiOperation({
    summary: 'List guards for an estate',
    description: 'Returns guard profiles in the current estate scope. SUPER_ADMIN must supply estateId.'
  })
  @ApiQuery({ name: 'estateId', required: false, example: ESTATE_ID_EXAMPLE, description: 'Estate scope. Required for SUPER_ADMIN.' })
  @ApiResponse({
    status: 200,
    description: 'Guards returned.',
    schema: {
      example: [
        {
          id: GUARD_ID_EXAMPLE,
          estateId: ESTATE_ID_EXAMPLE,
          userId: USER_ID_EXAMPLE,
          name: 'Ade Okafor',
          phone: '+2348000000004',
          deviceId: 'guard-device-001',
          status: 'ACTIVE'
        }
      ]
    }
  })
  findAll(@CurrentUser() user: RequestUser, @Query('estateId') estateId?: string) {
    return this.guardsService.findAll(user, estateId);
  }

  @Post()
  @RequireRole(UserRole.ESTATE_ADMIN, UserRole.SECURITY_SUPERVISOR)
  @RequireFeature(FeatureKey.GUARDS_MANAGE)
  @ApiOperation({
    summary: 'Create guard',
    description: 'Creates both a GUARD user account and its guard profile in the estate.'
  })
  @ApiBody({ type: CreateGuardDto })
  @ApiResponse({
    status: 201,
    description: 'Guard profile created.',
    schema: {
      example: {
        id: GUARD_ID_EXAMPLE,
        estateId: ESTATE_ID_EXAMPLE,
        userId: USER_ID_EXAMPLE,
        name: 'Ade Okafor',
        phone: '+2348000000200',
        deviceId: 'guard-device-002',
        status: 'ACTIVE'
      }
    }
  })
  @ApiValidationError()
  create(@Body() dto: CreateGuardDto, @CurrentUser() user: RequestUser) {
    return this.guardsService.create(dto, user);
  }
}
