import {
  Controller,
  Get,
  Put,
  Body,
  Query,
  UseGuards,
  Request,
} from '@nestjs/common';
import {
  ApiTags,
  ApiOperation,
  ApiBearerAuth,
  ApiResponse,
  ApiQuery,
} from '@nestjs/swagger';
import { ThemesService } from './themes.service';
import { SetThemeDto } from './dto';
import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard';
import { RolesGuard } from '../auth/guards/roles.guard';
import { Roles, UserRole } from '../../common/decorators/roles.decorator';

@ApiTags('Themes')
@Controller()
export class ThemesController {
  constructor(private readonly themesService: ThemesService) {}

  /**
   * Public endpoint — all services poll this to get the active theme.
   * No auth required so landing pages and unauthenticated clients can fetch it.
   */
  @Get('theme/current')
  @ApiOperation({ summary: 'Get the current active platform theme (public)' })
  @ApiResponse({ status: 200, description: 'Active theme ID and definition' })
  async getCurrent() {
    return this.themesService.getCurrent();
  }

  @Get('admin/themes')
  @ApiBearerAuth()
  @UseGuards(JwtAuthGuard, RolesGuard)
  @Roles(UserRole.SUPER_ADMIN)
  @ApiOperation({ summary: 'List all available themes (superadmin only)' })
  @ApiResponse({ status: 200, description: 'List of all 10 design themes' })
  async listThemes() {
    return {
      themes: this.themesService.getAvailableThemes(),
      current: await this.themesService.getCurrentThemeId(),
    };
  }

  @Put('admin/themes/active')
  @ApiBearerAuth()
  @UseGuards(JwtAuthGuard, RolesGuard)
  @Roles(UserRole.SUPER_ADMIN)
  @ApiOperation({ summary: 'Set the active platform theme (superadmin only)' })
  @ApiResponse({ status: 200, description: 'Theme activated successfully' })
  @ApiResponse({ status: 400, description: 'Invalid theme ID' })
  async setActive(@Body() dto: SetThemeDto, @Request() req: any) {
    const userId = req.user?.id ?? req.user?.sub ?? 'unknown';
    return this.themesService.setActive(dto.themeId, userId);
  }

  @Get('admin/themes/history')
  @ApiBearerAuth()
  @UseGuards(JwtAuthGuard, RolesGuard)
  @Roles(UserRole.SUPER_ADMIN)
  @ApiOperation({ summary: 'Get theme change history (superadmin only)' })
  @ApiQuery({ name: 'limit', required: false, type: Number, description: 'Max records (default 20)' })
  @ApiResponse({ status: 200, description: 'Theme change audit trail' })
  async getHistory(@Query('limit') limit?: number) {
    return this.themesService.getHistory(limit ?? 20);
  }
}
