import { Router } from "express";
import multer, { memoryStorage } from "multer";
import sharp from "sharp";
import fs from "fs";
import path from "path";
import { v4 as uuidv4 } from "uuid";

const router = Router();

const upload = multer({
  dest: "uploads/",
  storage: memoryStorage(),
  fileFilter: (_req, file, cb) => {
    if (file.mimetype.split("/")[0] === "image") {
      cb(null, true);
    } else {
      cb(new Error("Only images are allowed!"));
    }
  },
});

router.get("/", (_req, res) => {
  res.json({ ok: 1 });
});

router.get("/:filename", (req, res) => {
  res.sendFile(`${path.resolve("uploads")}/${req.params.filename}`);
});

router.get("/:file", (req, res) => {
  const fileName = req.params.file;

  console.log(fileName);

  try {
    const readStream = fs.createReadStream(
      `${path.join(__dirname, "uploads")}/${fileName}`
    );

    console.log(readStream);

    readStream.pipe(res);
  } catch (error) {
    if (error instanceof Error) {
      return res.json({ error: error.message });
    }
  }
});

router.post("/", upload.single("file"), async (req, res) => {
  if (!req.file) {
    return res.json({ error: "req.file" });
  }

  try {
    const filename = `${uuidv4()}.jpg`;

    await sharp(req.file.buffer)
      .resize({
        width: 728,
        height: 728,
        fit: "inside",
        withoutEnlargement: true,
      })
      .jpeg({ quality: 90 })
      .toFile(`uploads/${filename}`);

    return res.json({ file: filename });
  } catch (error) {
    if (error instanceof Error) {
      return res.json({ error: error.message });
    }
  }
});

const uploadRoute = router;

export default uploadRoute;
