import {
  Controller,
  Get,
  Put,
  Delete,
  Body,
  Query,
  UseGuards,
  HttpCode,
  HttpStatus,
} from '@nestjs/common';
import { ApiTags, ApiBearerAuth, ApiOperation, 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, type JwtPayload } from '../../../common/decorators/current-user.decorator';
import { CardLayoutService } from '../services/card-layout.service';
import { SetCardLayoutDto } from '../dto/set-card-layout.dto';

@ApiTags('CRM Card Layouts')
@ApiBearerAuth()
@Controller('crm/card-layouts')
@UseGuards(JwtAuthGuard)
export class CardLayoutsController {
  constructor(private readonly cardLayouts: CardLayoutService) {}

  @Get()
  @ApiOperation({ summary: 'Get effective card layout (user override or admin default)' })
  @ApiQuery({ name: 'entityType', required: true })
  @ApiQuery({ name: 'useDefault', required: false, description: 'Force admin default layout' })
  async getEffective(
    @CurrentUser() user: JwtPayload,
    @Query('entityType') entityType: string,
    @Query('useDefault') useDefault?: string,
  ): Promise<any> {
    const clubId = user.role === (UserRole.SUPER_ADMIN as string) ? null : user.clubId;
    const forceDefault = useDefault === 'true';
    return this.cardLayouts.getEffectiveLayout(clubId, entityType, user.sub, forceDefault);
  }

  @Put()
  @UseGuards(RolesGuard)
  @Roles(UserRole.SUPER_ADMIN, UserRole.CLUB_ADMIN)
  @ApiOperation({ summary: 'Set admin-default card layout' })
  async setAdminLayout(@CurrentUser() user: JwtPayload, @Body() dto: SetCardLayoutDto) {
    const clubId = user.role === (UserRole.SUPER_ADMIN as string) ? null : user.clubId;
    return this.cardLayouts.setAdminLayout(clubId, dto);
  }

  @Put('me')
  @ApiOperation({ summary: 'Set personal card layout override' })
  async setUserLayout(@CurrentUser() user: JwtPayload, @Body() dto: SetCardLayoutDto) {
    const clubId = user.role === (UserRole.SUPER_ADMIN as string) ? null : user.clubId;

    // If saveForAll and user is admin, also update admin default
    if (
      dto.saveForAll &&
      [UserRole.SUPER_ADMIN as string, UserRole.CLUB_ADMIN as string].includes(user.role)
    ) {
      await this.cardLayouts.setAdminLayout(clubId, dto);
    }

    return this.cardLayouts.setUserLayout(user.sub, clubId, dto);
  }

  @Delete('me')
  @HttpCode(HttpStatus.NO_CONTENT)
  @ApiOperation({ summary: 'Reset personal layout to admin default' })
  @ApiQuery({ name: 'entityType', required: true })
  async resetUserLayout(@CurrentUser() user: JwtPayload, @Query('entityType') entityType: string) {
    const clubId = user.role === (UserRole.SUPER_ADMIN as string) ? null : user.clubId;
    await this.cardLayouts.resetUserLayout(user.sub, clubId, entityType);
  }
}
