import { Express, Request, Response } from "express";
import { storagePut } from "./storage";
import { UploadedFile } from "express-fileupload";

export function setupUploadRoutes(app: Express) {
  app.post("/api/upload", async (req: Request, res: Response) => {
    try {
      const files = req.files as { [key: string]: UploadedFile };
      const file = files?.file as UploadedFile;
      const prefix = req.body.prefix as string;

      if (!file) {
        return res.status(400).json({ error: "No file provided" });
      }

      if (!prefix) {
        return res.status(400).json({ error: "No prefix provided" });
      }

      // Validate file size (5MB max)
      if (file.size > 5 * 1024 * 1024) {
        return res.status(400).json({ error: "File too large" });
      }

      // Validate file type
      const allowedTypes = ["image/jpeg", "image/png", "application/pdf"];
      if (!allowedTypes.includes(file.mimetype)) {
        return res.status(400).json({ error: "Invalid file type" });
      }

      // Upload to S3
      const filename = `${prefix}-${Date.now()}`;
      const { url } = await storagePut(filename, file.data, file.mimetype);

      res.json({ url });
    } catch (error) {
      console.error("Upload error:", error);
      res.status(500).json({ error: "Upload failed" });
    }
  });
}
