import { Request, Response, NextFunction } from 'express';
import { GetImageUseCase } from '../../application/use-cases/image/get-image.use-case';
import { ImageEntityType } from '../../application/ports/image-storage';

const FOLDER_TO_ENTITY_TYPE: Record<string, ImageEntityType> = {
  networks: 'network',
  tokens: 'token',
};

const parseFilename = (filename: string): { id: string } => {
  const id = filename.replace(/\.[^.]+$/, '');
  return { id };
};

export class ImageController {
  constructor(private readonly getImageUseCase: GetImageUseCase) {}

  getImage = async (req: Request, res: Response, next: NextFunction): Promise<void> => {
    try {
      const type = FOLDER_TO_ENTITY_TYPE[req.params.type];
      if (!type) {
        res.status(404).json({ success: false, message: 'Invalid image type' });
        return;
      }

      const { id } = parseFilename(req.params.filename);
      const image = await this.getImageUseCase.execute(type, id);

      res.set('Content-Type', image.contentType);
      res.set('Cache-Control', 'public, max-age=86400');
      res.status(200).send(image.buffer);
    } catch (error) {
      next(error);
    }
  };
}
