// ============================================================
// CustomFieldsController — REST-Endpoints fuer Custom Fields
// ============================================================

import {
  Controller,
  Get,
  Post,
  Patch,
  Put,
  Delete,
  Body,
  Param,
  Query,
  ParseUUIDPipe,
  HttpCode,
  HttpStatus,
  UseGuards,
} from '@nestjs/common';
import {
  ApiTags,
  ApiOperation,
  ApiBearerAuth,
  ApiParam,
  ApiQuery,
} from '@nestjs/swagger';
import { CustomFieldsService } from './custom-fields.service';
import { CreateCustomFieldDto, CustomFieldEntityType } from './dto/create-custom-field.dto';
import { UpdateCustomFieldDto } from './dto/update-custom-field.dto';
import { SetCustomFieldValuesDto } from './dto/set-custom-field-values.dto';
import { CurrentUser, JwtPayload } from '../common/decorators';
import { TenantGuard } from '../auth/guards/tenant.guard';
import { singleResponse } from '../common/dto/pagination.dto';

@ApiTags('Custom Fields')
@ApiBearerAuth('access-token')
@UseGuards(TenantGuard)
@Controller('custom-fields')
export class CustomFieldsController {
  constructor(private readonly customFieldsService: CustomFieldsService) {}

  // --------------------------------------------------------
  // Definitionen
  // --------------------------------------------------------

  @Post()
  @HttpCode(HttpStatus.CREATED)
  @ApiOperation({ summary: 'Feld-Definition erstellen' })
  async createDefinition(
    @CurrentUser() user: JwtPayload,
    @Body() dto: CreateCustomFieldDto,
  ) {
    const definition = await this.customFieldsService.createDefinition(
      user.tenantId!,
      dto,
    );
    return singleResponse(definition);
  }

  @Get()
  @ApiOperation({ summary: 'Alle Feld-Definitionen auflisten' })
  @ApiQuery({
    name: 'entityType',
    required: false,
    enum: CustomFieldEntityType,
    description: 'Filter nach Entity-Typ',
  })
  async findAllDefinitions(
    @CurrentUser() user: JwtPayload,
    @Query('entityType') entityType?: CustomFieldEntityType,
  ) {
    const definitions = await this.customFieldsService.findAllDefinitions(
      user.tenantId!,
      entityType,
    );
    return { data: definitions };
  }

  @Get(':id')
  @ApiOperation({ summary: 'Feld-Definition abrufen' })
  @ApiParam({ name: 'id', type: 'string', format: 'uuid' })
  async findOneDefinition(
    @CurrentUser() user: JwtPayload,
    @Param('id', ParseUUIDPipe) id: string,
  ) {
    const definition = await this.customFieldsService.findOneDefinition(
      user.tenantId!,
      id,
    );
    return singleResponse(definition);
  }

  @Patch(':id')
  @ApiOperation({ summary: 'Feld-Definition aktualisieren (Label, Options, Position, Required)' })
  @ApiParam({ name: 'id', type: 'string', format: 'uuid' })
  async updateDefinition(
    @CurrentUser() user: JwtPayload,
    @Param('id', ParseUUIDPipe) id: string,
    @Body() dto: UpdateCustomFieldDto,
  ) {
    const definition = await this.customFieldsService.updateDefinition(
      user.tenantId!,
      id,
      dto,
    );
    return singleResponse(definition);
  }

  @Delete(':id')
  @ApiOperation({ summary: 'Feld-Definition loeschen (CASCADE auf alle Werte!)' })
  @ApiParam({ name: 'id', type: 'string', format: 'uuid' })
  async removeDefinition(
    @CurrentUser() user: JwtPayload,
    @Param('id', ParseUUIDPipe) id: string,
  ) {
    const definition = await this.customFieldsService.removeDefinition(
      user.tenantId!,
      id,
    );
    return singleResponse(definition);
  }

  // --------------------------------------------------------
  // Werte
  // --------------------------------------------------------

  @Put(':entityId/values')
  @ApiOperation({ summary: 'Custom-Field-Werte fuer Entity setzen (Bulk-Upsert)' })
  @ApiParam({ name: 'entityId', type: 'string', format: 'uuid', description: 'Contact/Company/Deal ID' })
  async setValues(
    @CurrentUser() user: JwtPayload,
    @Param('entityId', ParseUUIDPipe) entityId: string,
    @Body() dto: SetCustomFieldValuesDto,
  ) {
    const result = await this.customFieldsService.setValues(
      user.tenantId!,
      entityId,
      dto,
    );
    return singleResponse(result);
  }

  @Get(':entityId/values')
  @ApiOperation({ summary: 'Custom-Field-Werte fuer Entity lesen' })
  @ApiParam({ name: 'entityId', type: 'string', format: 'uuid', description: 'Contact/Company/Deal ID' })
  async getValues(
    @CurrentUser() user: JwtPayload,
    @Param('entityId', ParseUUIDPipe) entityId: string,
  ) {
    const values = await this.customFieldsService.getValues(
      user.tenantId!,
      entityId,
    );
    return { data: values };
  }
}
