import {
  Controller,
  Post,
  Get,
  Delete,
  Param,
  UseGuards,
  UseInterceptors,
  UploadedFile,
  HttpCode,
  HttpStatus,
} from '@nestjs/common';
import { FileInterceptor } from '@nestjs/platform-express';
import { diskStorage } from 'multer';
import { existsSync, mkdirSync } from 'fs';
import { join } from 'path';
import { ApiTags, ApiOperation, ApiBearerAuth, ApiConsumes, ApiResponse } from '@nestjs/swagger';
import { ScreenshotsService } from './screenshots.service';
import { ScreenshotTokenGuard } from './guards/screenshot-token.guard';

const TMP_DIR = join(process.cwd(), '..', '..', 'data', 'screenshots', '.tmp');

@ApiTags('Screenshots')
@Controller('screenshots')
export class ScreenshotsController {
  constructor(private readonly screenshotsService: ScreenshotsService) {
    if (!existsSync(TMP_DIR)) {
      mkdirSync(TMP_DIR, { recursive: true });
    }
  }

  @Post('upload')
  @HttpCode(HttpStatus.CREATED)
  @UseGuards(ScreenshotTokenGuard)
  @ApiBearerAuth()
  @ApiOperation({ summary: 'Upload a screenshot' })
  @ApiConsumes('multipart/form-data')
  @ApiResponse({ status: 201, description: 'Screenshot uploaded' })
  @ApiResponse({ status: 401, description: 'Invalid token' })
  @ApiResponse({ status: 413, description: 'File too large' })
  @ApiResponse({ status: 422, description: 'Invalid format' })
  @UseInterceptors(
    FileInterceptor('image', {
      storage: diskStorage({
        destination: (_req, _file, cb) => {
          if (!existsSync(TMP_DIR)) mkdirSync(TMP_DIR, { recursive: true });
          cb(null, TMP_DIR);
        },
        filename: (_req, file, cb) => {
          cb(null, `upload_${Date.now()}_${Math.random().toString(36).slice(2)}`);
        },
      }),
      limits: { fileSize: 10 * 1024 * 1024 },
    }),
  )
  upload(@UploadedFile() file: Express.Multer.File) {
    const data = this.screenshotsService.upload(file);
    return { success: true, data };
  }

  @Delete(':id')
  @UseGuards(ScreenshotTokenGuard)
  @ApiBearerAuth()
  @ApiOperation({ summary: 'Delete a screenshot' })
  @ApiResponse({ status: 200, description: 'Screenshot deleted' })
  @ApiResponse({ status: 401, description: 'Invalid token' })
  @ApiResponse({ status: 404, description: 'Screenshot not found' })
  delete(@Param('id') id: string) {
    this.screenshotsService.delete(id);
    return { success: true, message: 'Screenshot deleted' };
  }

  @Get('info')
  @UseGuards(ScreenshotTokenGuard)
  @ApiBearerAuth()
  @ApiOperation({ summary: 'Server info' })
  @ApiResponse({ status: 200, description: 'Server information' })
  info() {
    const data = this.screenshotsService.getInfo();
    return { success: true, data };
  }
}
