import { Body, Controller, Get, Post } from '@nestjs/common';
import { ApiBody, ApiOperation, 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 } from '../common/swagger-docs';
import { CreateEstateDto } from './dto/create-estate.dto';
import { EstatesService } from './estates.service';

@ApiTags('Estates')
@ApiProtectedEndpoint()
@Controller({ path: 'estates', version: '1' })
export class EstatesController {
  constructor(private readonly estatesService: EstatesService) {}

  @Get()
  @RequireRole(UserRole.SUPER_ADMIN, UserRole.ESTATE_ADMIN)
  @RequireFeature(FeatureKey.ESTATES_VIEW)
  @ApiOperation({
    summary: 'List estates visible to the current user',
    description: 'SUPER_ADMIN and SALES_ADMIN receive all estates. ESTATE_ADMIN receives only their own estate.'
  })
  @ApiResponse({
    status: 200,
    description: 'Visible estates returned.',
    schema: {
      example: [
        {
          id: ESTATE_ID_EXAMPLE,
          name: 'GreenPark Estate',
          location: 'Lagos, Nigeria',
          settings: { timezone: 'Africa/Lagos', gates: ['Main Gate'] },
          branding: { primaryColor: '#0f766e' }
        }
      ]
    }
  })
  findAll(@CurrentUser() user: RequestUser) {
    return this.estatesService.findAll(user);
  }

  @Post()
  @RequireRole(UserRole.SUPER_ADMIN)
  @RequireFeature(FeatureKey.ESTATES_MANAGE)
  @ApiOperation({
    summary: 'Create an estate',
    description: 'Onboards a new estate. SUPER_ADMIN always can create estates; SALES_ADMIN can create estates when the ESTATES_MANAGE feature is enabled.'
  })
  @ApiBody({ type: CreateEstateDto })
  @ApiResponse({
    status: 201,
    description: 'Estate created.',
    schema: {
      example: {
        id: ESTATE_ID_EXAMPLE,
        name: 'GreenPark Estate',
        location: 'Lagos, Nigeria',
        settings: { timezone: 'Africa/Lagos' },
        branding: { primaryColor: '#0f766e' }
      }
    }
  })
  @ApiValidationError()
  create(@Body() dto: CreateEstateDto, @CurrentUser() user: RequestUser) {
    return this.estatesService.create(dto, user);
  }
}
