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 { 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 ext = req.file.originalname?.split(".").pop() || "jpg"
    const path = `misc/${req.auth.userId}/${key}.${ext}`

    const url = await uploadImage({
      bucket: "deal",
      path,
      fileBuffer: req.file.buffer,
      contentType: req.file.mimetype,
    })

    enqueueAuditFromRequest(
      req,
      AUDIT_ACTIONS.MEDIA.UPLOAD,
      buildAuditMeta({
        entityType: "MEDIA",
        entityId: path,
        extra: { contentType: req.file.mimetype },
      })
    )

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

module.exports = router

