import type { Request, Response, NextFunction } from 'express';
import { imageContentType, objectKey } from '../middlewares/upload.js';
import { errorResponse, successResponse } from '../utils/response.js';
import { fileUrl, putFile } from '../utils/storage.js';

// POST /uploads/images: stores one image in S3 under the caller's organization and returns
// its key (to save on a record) and a URL to show it now. Project documents don't go here.
async function uploadImage(req: Request, res: Response, next: NextFunction) {
  try {
    if (!req.file) return void errorResponse(res, 'Choose an image to upload', 400, [{ field: 'file', message: 'Required' }]);
    const { organizationId } = req.tenant!;
    const contentType = imageContentType(req.file.originalname);
    const key = await putFile(objectKey(`orgs/${organizationId}/images`, req.file.originalname), req.file.buffer, contentType);
    return successResponse(res, 'Image uploaded', {
      key,
      url: await fileUrl(key),
      contentType,
      size: req.file.size,
      fileName: req.file.originalname,
    }, 201);
  } catch (error) {
    next(error);
    return;
  }
}

export { uploadImage };
