import {
  Controller,
  Get,
  Post,
  Patch,
  Delete,
  Param,
  Body,
  Query,
  UseGuards,
  HttpCode,
  HttpStatus,
  ParseUUIDPipe,
} from '@nestjs/common';
import { ApiTags, ApiBearerAuth, ApiOperation, ApiResponse, ApiQuery } from '@nestjs/swagger';
import { JwtAuthGuard } from '../../auth/guards/jwt-auth.guard';
import { RolesGuard } from '../../auth/guards/roles.guard';
import { Roles, UserRole } from '../../../common/decorators/roles.decorator';
import { CurrentUser } from '../../../common/decorators/current-user.decorator';
import { UserFieldsService } from '../services/user-fields.service';
import { CreateFieldDto } from '../dto/create-field.dto';
import { UpdateFieldDto } from '../dto/update-field.dto';
import { ReorderFieldsDto } from '../dto/reorder-fields.dto';

@ApiTags('CRM Custom Fields')
@ApiBearerAuth()
@Controller('crm/fields')
@UseGuards(JwtAuthGuard)
export class FieldsController {
  constructor(private readonly userFields: UserFieldsService) {}

  @Get()
  @ApiOperation({ summary: 'Get custom fields for entity type' })
  @ApiQuery({ name: 'entityType', required: true })
  @ApiResponse({ status: 200 })
  async findAll(@CurrentUser() user: any, @Query('entityType') entityType: string) {
    const clubId = user.role === UserRole.SUPER_ADMIN ? null : user.clubId;
    return this.userFields.findByEntity(clubId, entityType);
  }

  @Get(':id')
  @ApiOperation({ summary: 'Get custom field by ID' })
  @ApiResponse({ status: 200 })
  async getById(@Param('id', ParseUUIDPipe) id: string) {
    return this.userFields.getById(id);
  }

  @Post()
  @UseGuards(RolesGuard)
  @Roles(UserRole.SUPER_ADMIN, UserRole.CLUB_ADMIN)
  @ApiOperation({ summary: 'Create a custom field' })
  @ApiResponse({ status: 201 })
  async create(@CurrentUser() user: any, @Body() dto: CreateFieldDto) {
    const clubId = user.role === UserRole.SUPER_ADMIN ? null : user.clubId;
    return this.userFields.create(clubId, dto);
  }

  @Patch(':id')
  @UseGuards(RolesGuard)
  @Roles(UserRole.SUPER_ADMIN, UserRole.CLUB_ADMIN)
  @ApiOperation({ summary: 'Update a custom field' })
  async update(@Param('id', ParseUUIDPipe) id: string, @Body() dto: UpdateFieldDto) {
    return this.userFields.update(id, dto);
  }

  @Delete(':id')
  @UseGuards(RolesGuard)
  @Roles(UserRole.SUPER_ADMIN, UserRole.CLUB_ADMIN)
  @HttpCode(HttpStatus.NO_CONTENT)
  @ApiOperation({ summary: 'Deactivate a custom field' })
  async remove(@Param('id', ParseUUIDPipe) id: string) {
    await this.userFields.deactivate(id);
  }

  @Post('reorder')
  @HttpCode(HttpStatus.OK)
  @UseGuards(RolesGuard)
  @Roles(UserRole.SUPER_ADMIN, UserRole.CLUB_ADMIN)
  @ApiOperation({ summary: 'Reorder custom fields' })
  async reorder(@Body() dto: ReorderFieldsDto) {
    await this.userFields.reorder(dto.fieldIds);
  }
}
