import { Controller, Get, Patch, Body, Query, UseGuards } from '@nestjs/common';
import { ApiTags, ApiBearerAuth, ApiOperation, ApiQuery } from '@nestjs/swagger';
import { JwtAuthGuard } from '../../auth/guards/jwt-auth.guard';
import { CurrentUser, JwtPayload } from '../../../common/decorators/current-user.decorator';
import { RequireModule } from '../../../common/decorators/require-module.decorator';
import { ModuleGuard } from '../../../common/guards/module.guard';
import { Roles, UserRole } from '../../../common/decorators/roles.decorator';
import { RolesGuard } from '../../auth/guards/roles.guard';
import { PrismaService } from '../../../prisma/prisma.service';
import { WidgetSettingsService } from '../services/widget-settings.service';
import { UpdateWidgetSettingsDto } from '../dto/widget-settings.dto';

@ApiTags('Booking / Widget Settings')
@ApiBearerAuth()
@Controller('booking/widget-settings')
@UseGuards(JwtAuthGuard, ModuleGuard, RolesGuard)
@RequireModule('booking')
@Roles(UserRole.CLUB_ADMIN, UserRole.SUPER_ADMIN)
export class BookingWidgetSettingsController {
  constructor(
    private readonly widgetSettings: WidgetSettingsService,
    private readonly prisma: PrismaService,
  ) {}

  @Get()
  @ApiOperation({ summary: 'Get widget settings' })
  async getSettings(@CurrentUser() user: JwtPayload) {
    // eslint-disable-next-line @typescript-eslint/no-unsafe-return
    return this.widgetSettings.getSettings(user.clubId);
  }

  @Patch()
  @ApiOperation({ summary: 'Update widget settings' })
  async updateSettings(@CurrentUser() user: JwtPayload, @Body() dto: UpdateWidgetSettingsDto) {
    return this.widgetSettings.updateSettings(user.clubId, dto);
  }

  @Get('embed-code')
  @ApiOperation({ summary: 'Generate embed code snippets for the widget' })
  @ApiQuery({ name: 'apiKey', type: String, description: 'API key for the widget' })
  async getEmbedCode(@CurrentUser() user: JwtPayload, @Query('apiKey') apiKey: string) {
    const club = await this.prisma.club.findUniqueOrThrow({
      where: { id: user.clubId },
      select: { slug: true },
    });

    return this.widgetSettings.generateEmbedCode(club.slug, apiKey || 'YOUR_API_KEY');
  }
}
