import {
  Controller,
  Get,
  Patch,
  Post,
  Delete,
  Body,
  UseGuards,
  UseInterceptors,
  UploadedFile,
  ParseFilePipe,
  MaxFileSizeValidator,
  FileTypeValidator,
} from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { FileInterceptor } from '@nestjs/platform-express';
import { SettingsService } from './settings.service';
import { UpdatePdfSettingsDto } from './dto/update-pdf-settings.dto';
import { JwtAuthGuard } from '../auth/guards/jwt-auth.guard';
import { AbilitiesGuard } from '../auth/guards/abilities.guard';
import { CanUpdate } from '../auth/decorators/check-ability.decorator';

@Controller('settings')
@UseGuards(JwtAuthGuard, AbilitiesGuard)
export class SettingsController {
  constructor(
    private readonly settingsService: SettingsService,
    private readonly configService: ConfigService,
  ) {}

  /**
   * Feature flags - tells the frontend which optional services are configured.
   * No ability decorator = any authenticated user can access.
   */
  @Get('features')
  getFeatureFlags() {
    return {
      copilot: !!this.configService.get('ANTHROPIC_API_KEY'),
      flightTracking: !!this.configService.get('AVIATIONSTACK_API_KEY'),
      signalMessaging: !!this.configService.get('SIGNAL_API_URL'),
      gpsTracking: !!this.configService.get('TRACCAR_API_URL'),
    };
  }

  /**
   * Get app timezone - any authenticated user can read this
   */
  @Get('timezone')
  getTimezone() {
    return this.settingsService.getTimezone();
  }

  /**
   * Update app timezone - admin only
   */
  @Patch('timezone')
  @CanUpdate('Settings')
  updateTimezone(@Body() dto: { timezone: string }) {
    return this.settingsService.updateTimezone(dto.timezone);
  }

  @Get('pdf')
  @CanUpdate('Settings') // Admin-only (Settings subject is admin-only)
  getPdfSettings() {
    return this.settingsService.getPdfSettings();
  }

  @Patch('pdf')
  @CanUpdate('Settings')
  updatePdfSettings(@Body() dto: UpdatePdfSettingsDto) {
    return this.settingsService.updatePdfSettings(dto);
  }

  @Post('pdf/logo')
  @CanUpdate('Settings')
  @UseInterceptors(FileInterceptor('logo'))
  uploadLogo(
    @UploadedFile(
      new ParseFilePipe({
        validators: [
          new MaxFileSizeValidator({ maxSize: 2 * 1024 * 1024 }), // 2MB
          new FileTypeValidator({ fileType: /(png|jpeg|jpg|svg\+xml)/ }),
        ],
      }),
    )
    file: Express.Multer.File,
  ) {
    return this.settingsService.uploadLogo(file);
  }

  @Delete('pdf/logo')
  @CanUpdate('Settings')
  deleteLogo() {
    return this.settingsService.deleteLogo();
  }
}
