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, RESIDENT_ID_EXAMPLE, USER_ID_EXAMPLE } from '../common/swagger-docs';
import { CreateResidentDto } from './dto/create-resident.dto';
import { ResidentsService } from './residents.service';

@ApiTags('Residents')
@ApiProtectedEndpoint()
@Controller({ path: 'residents', version: '1' })
export class ResidentsController {
  constructor(private readonly residentsService: ResidentsService) {}

  @Get()
  @RequireRole(UserRole.ESTATE_ADMIN, UserRole.SECURITY_SUPERVISOR, UserRole.RESIDENT)
  @RequireFeature(FeatureKey.RESIDENTS_VIEW)
  @ApiOperation({
    summary: 'List or search residents',
    description: 'Returns residents for the resolved estate scope. Use q to search name, unit, or phone.'
  })
  @ApiQuery({ name: 'estateId', required: false, example: ESTATE_ID_EXAMPLE, description: 'Estate scope. Required for SUPER_ADMIN.' })
  @ApiQuery({ name: 'q', required: false, example: 'Ada', description: 'Optional search text.' })
  @ApiResponse({
    status: 200,
    description: 'Residents returned.',
    schema: {
      example: [
        {
          id: RESIDENT_ID_EXAMPLE,
          estateId: ESTATE_ID_EXAMPLE,
          userId: USER_ID_EXAMPLE,
          unit: 'A12',
          phone: '+2348000000003',
          name: 'Ade Okafor',
          status: 'ACTIVE'
        }
      ]
    }
  })
  findAll(@CurrentUser() user: RequestUser, @Query('estateId') estateId?: string, @Query('q') q?: string) {
    return this.residentsService.findAll(user, estateId, q);
  }

  @Post()
  @RequireRole(UserRole.ESTATE_ADMIN, UserRole.SECURITY_SUPERVISOR)
  @RequireFeature(FeatureKey.RESIDENTS_MANAGE)
  @ApiOperation({
    summary: 'Create resident',
    description: 'Creates both a RESIDENT user account and its resident profile in the estate.'
  })
  @ApiBody({ type: CreateResidentDto })
  @ApiResponse({
    status: 201,
    description: 'Resident profile created.',
    schema: {
      example: {
        id: RESIDENT_ID_EXAMPLE,
        estateId: ESTATE_ID_EXAMPLE,
        userId: USER_ID_EXAMPLE,
        name: 'Ade Okafor',
        phone: '+2348000000300',
        unit: 'A12',
        status: 'ACTIVE'
      }
    }
  })
  @ApiValidationError()
  create(@Body() dto: CreateResidentDto, @CurrentUser() user: RequestUser) {
    return this.residentsService.create(dto, user);
  }
}
