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 { ApiNotFoundError, ApiProtectedEndpoint, ApiValidationError, ESTATE_ID_EXAMPLE, GUARD_ID_EXAMPLE } from '../common/swagger-docs';
import { CreateIncidentDto } from './dto/create-incident.dto';
import { IncidentsService } from './incidents.service';

@ApiTags('Incidents')
@ApiProtectedEndpoint()
@Controller({ path: 'incidents', version: '1' })
export class IncidentsController {
  constructor(private readonly incidentsService: IncidentsService) {}

  @Get()
  @RequireRole(UserRole.ESTATE_ADMIN, UserRole.SECURITY_SUPERVISOR, UserRole.GUARD)
  @RequireFeature(FeatureKey.INCIDENTS_VIEW)
  @ApiOperation({
    summary: 'List incidents',
    description: 'Returns recent incident reports for the resolved estate scope.'
  })
  @ApiQuery({ name: 'estateId', required: false, example: ESTATE_ID_EXAMPLE, description: 'Estate scope. Required for SUPER_ADMIN.' })
  @ApiResponse({
    status: 200,
    description: 'Incidents returned.',
    schema: {
      example: [
        {
          id: 'incident-uuid',
          estateId: ESTATE_ID_EXAMPLE,
          guardId: GUARD_ID_EXAMPLE,
          type: 'SECURITY',
          description: 'Suspicious activity near the main gate',
          metadata: { gate: 'Main Gate' }
        }
      ]
    }
  })
  findAll(@CurrentUser() user: RequestUser, @Query('estateId') estateId?: string) {
    return this.incidentsService.findAll(user, estateId);
  }

  @Post()
  @RequireRole(UserRole.ESTATE_ADMIN, UserRole.SECURITY_SUPERVISOR, UserRole.GUARD)
  @RequireFeature(FeatureKey.INCIDENTS_MANAGE)
  @ApiOperation({
    summary: 'Create incident',
    description: 'Creates an estate-scoped incident report. GUARD users must submit their own guardId.'
  })
  @ApiBody({ type: CreateIncidentDto })
  @ApiResponse({
    status: 201,
    description: 'Incident created.',
    schema: {
      example: {
        id: 'incident-uuid',
        estateId: ESTATE_ID_EXAMPLE,
        guardId: GUARD_ID_EXAMPLE,
        type: 'SECURITY',
        description: 'Suspicious activity near the main gate',
        metadata: { gate: 'Main Gate' }
      }
    }
  })
  @ApiNotFoundError('Active guard')
  @ApiValidationError()
  create(@Body() dto: CreateIncidentDto, @CurrentUser() user: RequestUser) {
    return this.incidentsService.create(dto, user);
  }
}
