const express = require("express")
const { v4: uuidv4 } = require("uuid")

const requireAuth = require("../middleware/requireAuth")
const requireNotRestricted = require("../middleware/requireNotRestricted")
const { upload } = require("../middleware/upload.middleware")
const { uploadImage } = require("../services/uploadImage.service")
const { makeWebp } = require("../utils/processImage")
const { enqueueAuditFromRequest, buildAuditMeta } = require("../services/audit.service")
const { AUDIT_ACTIONS } = require("../services/auditActions")

const router = express.Router()

router.post(
  "/image",
  requireAuth,
  requireNotRestricted({ checkSuspend: true }),
  upload.single("file"),
  async (req, res) => {
  try {
    if (!req.file) return res.status(400).json({ error: "Dosya zorunlu" })
    if (!req.file.mimetype?.startsWith("image/")) {
      return res.status(400).json({ error: "Sadece resim kabul edilir" })
    }

    const key = uuidv4()
    const webpBuffer = await makeWebp(req.file.buffer, { quality: 40 })
    const path = `misc/${req.auth.userId}/${key}.webp`

    const url = await uploadImage({
      bucket: "deal",
      path,
      fileBuffer: webpBuffer,
      contentType: "image/webp",
    })

    enqueueAuditFromRequest(
      req,
      AUDIT_ACTIONS.MEDIA.UPLOAD,
      buildAuditMeta({
        entityType: "MEDIA",
        entityId: path,
        extra: { contentType: "image/webp" },
      })
    )

    res.json({ url })
  } catch (err) {
    console.error(err)
    res.status(500).json({ error: "Sunucu hatasi" })
  }
  }
)

module.exports = router

