import {
  Controller,
  Get,
  Param,
  Res,
  NotFoundException,
  UseInterceptors,
} from '@nestjs/common';
import { FastifyReply } from 'fastify';
import * as path from 'path';
import * as fs from 'fs';
import { Public } from '@/models/users/decorators/public-route';

@Controller('photos')
export class ServePhotos {
  @Public()
  @Get(':shootingId/:filename')
  async servePhoto(
    @Param('shootingId') shootingId: string,
    @Param('filename') filename: string,
    @Res() reply: FastifyReply,
  ) {
    const filePath = path.resolve(
      process.env.UPLOAD_PATH || __dirname,
      `shootings/${shootingId}/${filename}`,
    );

    if (!fs.existsSync(filePath)) {
      throw new NotFoundException('File not found');
    }

    const contentType = this.getContentType(filename);

    reply.header('Content-Type', contentType);

    try {
      const fileStream = fs.createReadStream(filePath);

      fileStream.on('error', (error) => {
        console.error('File read error:', error);
        reply.status(500).send('Error reading file');
      });

      return reply.send(fileStream);
    } catch (error) {
      console.error('Serve file error:', error);
      reply.status(500).send('Internal server error');
    }
  }

  private getContentType(filename: string): string {
    const ext = path.extname(filename).toLowerCase();
    switch (ext) {
      case '.jpg':
      case '.jpeg':
        return 'image/jpeg';
      case '.png':
        return 'image/png';
      case '.gif':
        return 'image/gif';
      case '.webp':
        return 'image/webp';
      case '.svg':
        return 'image/svg+xml';
      case '.bmp':
        return 'image/bmp';
      case '.webmanifest':
        return 'application/manifest+json';
      default:
        return 'application/octet-stream';
    }
  }
}
