import { Body, Controller, Get, Patch } from '@nestjs/common';
import { ApiBody, ApiOperation, ApiResponse, ApiTags } from '@nestjs/swagger';
import { UserRole } from '@prisma/client';
import { RequireRole } from '../auth/require-role.decorator';
import { CurrentUser } from '../common/current-user.decorator';
import { RequestUser } from '../common/request-user';
import { ApiProtectedEndpoint, ApiValidationError } from '../common/swagger-docs';
import { FeatureKey } from '../features/feature-catalog';
import { RequireFeature } from '../features/require-feature.decorator';
import { UpdateMyProfileDto } from './dto/profile.dto';
import { ProfileService } from './profile.service';

@ApiTags('Profile')
@ApiProtectedEndpoint()
@Controller({ path: 'profile', version: '1' })
export class ProfileController {
  constructor(private readonly profileService: ProfileService) {}

  @Get('me')
  @RequireRole(UserRole.ESTATE_ADMIN, UserRole.SECURITY_SUPERVISOR, UserRole.GUARD, UserRole.RESIDENT)
  @RequireFeature(FeatureKey.PROFILE_VIEW)
  @ApiOperation({
    summary: 'View current profile',
    description:
      'Returns the signed-in user profile, resident or guard role profile, profile completion checklist, and resident-safe estate plan comparison.'
  })
  @ApiResponse({
    status: 200,
    description: 'Profile returned.',
    schema: {
      example: {
        completion: { completion: 86, complete: false, missing: ['Profile confirmation'] },
        currentPlan: { code: 'STARTER', name: 'GateWise Starter', features: ['VISITOR_PASSES_CREATE'] },
        planComparison: { showPricing: false, upgrades: [{ code: 'SECURE', name: 'GateWise Secure' }] }
      }
    }
  })
  getMe(@CurrentUser() user: RequestUser) {
    return this.profileService.getMe(user);
  }

  @Get('demo-access')
  @RequireRole(UserRole.ESTATE_ADMIN)
  @RequireFeature(FeatureKey.PROFILE_VIEW)
  @ApiOperation({
    summary: 'Verify protected demo access',
    description:
      'Confirms the signed-in estate admin has an approved, active, time-limited demo session before the WebApp opens the demo workspace.'
  })
  @ApiResponse({
    status: 200,
    description: 'Demo access decision returned.',
    schema: {
      example: {
        approved: true,
        roleRequired: 'ESTATE_ADMIN',
        estate: { id: 'estate-uuid', name: 'Crown View Estate' },
        expiresAt: '2026-05-24T18:00:00.000Z',
        maxSessionMinutes: 120
      }
    }
  })
  getDemoAccess(@CurrentUser() user: RequestUser) {
    return this.profileService.getDemoAccess(user);
  }

  @Patch('me')
  @RequireRole(UserRole.ESTATE_ADMIN, UserRole.SECURITY_SUPERVISOR, UserRole.GUARD, UserRole.RESIDENT)
  @RequireFeature(FeatureKey.PROFILE_MANAGE)
  @ApiOperation({
    summary: 'Update current profile',
    description:
      'Updates names, address, email, block/flat data, profile image URLs, emergency contact, household members, and confirmation status. Image payloads store processing metadata for resized/compressed assets.'
  })
  @ApiBody({ type: UpdateMyProfileDto })
  @ApiResponse({
    status: 200,
    description: 'Profile updated with recalculated completion.',
    schema: { example: { completion: { completion: 100, complete: true, missing: [] } } }
  })
  @ApiValidationError()
  updateMe(@CurrentUser() user: RequestUser, @Body() dto: UpdateMyProfileDto) {
    return this.profileService.updateMe(user, dto);
  }
}
