import { Controller, Get, Param, Res, NotFoundException } 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';
import * as mime from 'mime-types';

@Controller('files')
export class ServeFile {
  @Public()
  @Get('*')
  async serveFile(@Param('*') filePath: string, @Res() reply: FastifyReply) {
    const fullPath = path.resolve(
      process.env.UPLOAD_PATH || __dirname,
      filePath,
    );

    const normalizedPath = path.normalize(fullPath);
    const uploadBasePath = path.resolve(process.env.UPLOAD_PATH || __dirname);

    if (!normalizedPath.startsWith(uploadBasePath)) {
      throw new NotFoundException('File not found');
    }

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

    const mimeType = mime.lookup(normalizedPath) || 'application/octet-stream';
    reply.header('Content-Type', mimeType);
    reply.header('Cache-Control', 'no-cache');

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

      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');
    }
  }
}
