import { Body, Controller, Get, Param, Patch, Post, Query } from '@nestjs/common';
import { ApiBody, ApiOperation, ApiParam, 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 } from '../common/swagger-docs';
import { SendNotificationDto } from './dto/send-notification.dto';
import { NotificationsService } from './notifications.service';

@ApiTags('Notifications')
@ApiProtectedEndpoint()
@Controller({ path: 'notifications', version: '1' })
export class NotificationsController {
  constructor(private readonly notificationsService: NotificationsService) {}

  @Get('me')
  @RequireRole(UserRole.ESTATE_ADMIN, UserRole.SECURITY_SUPERVISOR, UserRole.GUARD, UserRole.RESIDENT)
  @ApiOperation({
    summary: 'List my in-app notifications',
    description: 'Returns visitor check-in/out alerts, estate announcements, request responses, and security alerts for the signed-in user.'
  })
  @ApiQuery({ name: 'unreadOnly', required: false, example: 'true' })
  @ApiResponse({ status: 200, description: 'Notifications returned.' })
  listMine(@CurrentUser() user: RequestUser, @Query('unreadOnly') unreadOnly?: string) {
    return this.notificationsService.listMine(user, unreadOnly);
  }

  @Patch(':id/read')
  @RequireRole(UserRole.ESTATE_ADMIN, UserRole.SECURITY_SUPERVISOR, UserRole.GUARD, UserRole.RESIDENT)
  @ApiOperation({ summary: 'Mark notification as read', description: 'Marks one signed-in user notification as read.' })
  @ApiParam({ name: 'id', example: 'notification-uuid' })
  @ApiResponse({ status: 200, description: 'Notification marked read.' })
  markRead(@Param('id') id: string, @CurrentUser() user: RequestUser) {
    return this.notificationsService.markRead(id, user);
  }

  @Post('send')
  @RequireRole(UserRole.ESTATE_ADMIN, UserRole.SECURITY_SUPERVISOR)
  @RequireFeature(FeatureKey.NOTIFICATIONS_SEND)
  @ApiOperation({
    summary: 'Queue notification request',
    description:
      'Records a notification request for SMS, WhatsApp, or push delivery. Current implementation queues/audits the request and does not call an external provider.'
  })
  @ApiBody({ type: SendNotificationDto })
  @ApiResponse({
    status: 201,
    description: 'Notification request accepted.',
    schema: {
      example: {
        status: 'QUEUED',
        channel: 'SMS',
        criticalPath: false
      }
    }
  })
  @ApiValidationError()
  send(@Body() dto: SendNotificationDto, @CurrentUser() user: RequestUser) {
    return this.notificationsService.send(dto, user);
  }
}
