const express = require("express");
const router = express.Router();
const authorize = require("../../../../middlewares/authorize-sapps");
const saldoAwalClientService = require("./saldoAwalClient.service");
const multer = require("multer");
const path = require("path");
const fs = require("fs");

const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    const uploadPath = path.join(process.cwd(), "public/data/imports");

    // pastikan folder ada
    if (!fs.existsSync(uploadPath)) {
      fs.mkdirSync(uploadPath, { recursive: true });
    }

    cb(null, uploadPath);
  },

  filename: (req, file, cb) => {
    // pakai nama asli (aman)
    const safeName = file.originalname.replace(/\s+/g, "-");
    cb(null, safeName);
  },
});

const upload = multer({
  storage,
  fileFilter: (req, file, cb) => {
    const allowedExt = [".xlsx", ".xls"];
    const ext = path.extname(file.originalname).toLowerCase();

    if (!allowedExt.includes(ext)) {
      return cb(new Error("Only Excel files are allowed (.xlsx, .xls)"));
    }

    cb(null, true);
  },
});

router.post("/create", authorize(), create);
router.post("/", authorize(), getAll);
router.post(
  "/upload-saldo-awal",
  authorize(),
  upload.single("file"),
  (req, res, next) => {
    if (!req.file) {
      return res.status(400).json({ message: "File is required" });
    }

    // simpan filename dari multer
    req.body.filename = req.file.filename;

    next();
  },
  uploadSaldoAwal
);
router.get("/filter", authorize(), filter);
router.get("/option", authorize(), option);
router.get("/count", authorize(), count);
router.get("/get-uploads", authorize(), getAllSaldoUpload);
router.put("/:id", authorize(), update);
router.put("/enabled/:id", authorize(), enabled);
router.delete("/:id", authorize(), _delete);

module.exports = router;

function uploadSaldoAwal(req, res, next) {
  if (!req.file) {
    return res.status(400).json({
      success: false,
      message: "File is required",
    });
  }

  const filePath = path.join(process.cwd(), "public", "data", "imports", req.file.filename);

  // Cek apakah file ada
  if (!fs.existsSync(filePath)) {
    return res.status(404).json({
      success: false,
      message: "File not found on server",
    });
  }

  // Lanjutkan proses
  const saldoAwalData = {
    ...req.body,
    filename: req.file.filename,
  };

  saldoAwalClientService
    .uploadSaldoAwal(saldoAwalData)
    .then((result) => res.json(result))
    .catch(next);
}

function getAllSaldoUpload(req, res, next) {
  saldoAwalClientService
    .getAllSaldoUpload()
    .then((result) => res.json(result))
    .catch(next);
}

function create(req, res, next) {
  saldoAwalClientService
    .create(req.body)
    .then((result) => res.json(result))
    .catch(next);
}

function getAll(req, res, next) {
  saldoAwalClientService
    .getAll(req.body)
    .then((result) => res.json(result))
    .catch(next);
}

function filter(req, res, next) {
  saldoAwalClientService
    .filter(req.query)
    .then((result) => res.json(result))
    .catch(next);
}

function option(req, res, next) {
  saldoAwalClientService
    .option()
    .then((result) => res.json(result))
    .catch(next);
}

function count(req, res, next) {
  saldoAwalClientService
    .count()
    .then((result) => res.json(result))
    .catch(next);
}

function update(req, res, next) {
  saldoAwalClientService
    .update(req.params.id, req.body)
    .then((result) => res.json(result))
    .catch(next);
}

function enabled(req, res, next) {
  saldoAwalClientService
    .enabled(req.params.id, req.body)
    .then((result) => res.json(result))
    .catch(next);
}

function _delete(req, res, next) {
  saldoAwalClientService
    .delete(req.params.id)
    .then((result) => res.json(result))
    .catch(next);
}
