const express = require("express");
const router = express.Router();
const multer = require("multer");
const fs = require("fs");
const path = require("path");
const authorize = require("../../../../middlewares/authorize-sapps");
const tenderVendorService = require("./tenderVendor.service");
const redisClient = require('../../../../redisClient');

// Multer configuration for file uploads
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    const dest = path.resolve(__dirname, "../../../../public/data/documents/tendervendors");
    
    // Auto create folder if not exists
    if (!fs.existsSync(dest)) {
      fs.mkdirSync(dest, { recursive: true });
    }
    
    cb(null, dest);
  },
  filename: function (req, file, cb) {
    const dest = path.resolve(__dirname, "../../../../public/data/documents/tendervendors");
    
    // Check if file with same original name already exists
    // Pattern: timestamp-originalname.pdf
    // We'll search for files that have the same original name (after the timestamp prefix)
    try {
      const files = fs.readdirSync(dest);
      const originalName = file.originalname;
      
      // Find existing files with the same original name
      // Files follow pattern: timestamp-originalname, so we check if file ends with "-originalName"
      const existingFiles = files.filter(f => {
        // Check if file matches pattern: *-originalName (where * is timestamp)
        // This handles both "timestamp-originalName" and exact "originalName" matches
        const lastDashIndex = f.lastIndexOf("-");
        if (lastDashIndex !== -1) {
          const nameAfterDash = f.substring(lastDashIndex + 1);
          return nameAfterDash === originalName;
        }
        // Also check if file is exactly the original name (no timestamp prefix)
        return f === originalName;
      });
      
      // Delete existing files with the same original name
      existingFiles.forEach(existingFile => {
        const existingFilePath = path.join(dest, existingFile);
        try {
          if (fs.existsSync(existingFilePath)) {
            fs.unlinkSync(existingFilePath);
            console.log(`Deleted existing file: ${existingFile}`);
          }
        } catch (err) {
          console.error(`Error deleting existing file ${existingFile}:`, err);
        }
      });
    } catch (err) {
      console.error("Error checking for existing files:", err);
    }
    
    // Generate new filename with timestamp
    cb(null, Date.now() + "-" + file.originalname);
  },
});

const upload = multer({
  storage: storage,
  limits: {
    fileSize: 5 * 1024 * 1024, // 5MB max
  },
  fileFilter: function (req, file, cb) {
    // Only allow PDF files
    if (file.mimetype !== "application/pdf") {
      return cb(new Error("Hanya file PDF yang diperbolehkan!"));
    }
    cb(null, true);
  },
});

// Registration endpoint (no authorization required for public registration)
router.post("/register", upload.fields([
  { name: "nib_file", maxCount: 1 },
  { name: "npwp_file", maxCount: 1 },
  { name: "siup_file", maxCount: 1 },
  { name: "sertifikat_file", maxCount: 1 },
]), registerTenderVendor);

router.post("/create", authorize(), create);
router.post("/", authorize(), getAll);
router.post("/option", authorize(), option);
router.get("/count", authorize(), count);
router.get("/by-user-id/:userId", authorize(), getByUserId);
router.put("/:id", authorize(), update);
router.put('/enabled/:id', authorize(), enabled);
router.delete("/:id", authorize(), _delete);

module.exports = router;

function registerTenderVendor(req, res, next) {
    const files = {
        nib_file: req.files?.nib_file?.[0] || null,
        npwp_file: req.files?.npwp_file?.[0] || null,
        siup_file: req.files?.siup_file?.[0] || null,
        sertifikat_file: req.files?.sertifikat_file?.[0] || null,
    };

    tenderVendorService
        .registerTenderVendor(req.body, files)
        .then((result) => res.json(result))
        .catch(next);
}

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


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


async function option(req, res, next) {
    try {
        // Membuat cacheKey
        const cacheKey = `provinces-options`;

        // Mengecek apakah data sudah ada di Redis
        const cachedData = await redisClient.get(cacheKey);
        if (cachedData) {
            return res.json(JSON.parse(cachedData));
        }

        // Jika tidak ada, panggil tenderVendorService.option()
        const result = await tenderVendorService.option();

        // Simpan hasilnya ke Redis dengan expire time misalnya 60 detik
        await redisClient.setEx(cacheKey, 60, JSON.stringify(result));

        // Kembalikan response JSON dari hasil panggilan service
        return res.json(result);
    } catch (error) {
        return next(error);
    }
}

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

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

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

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

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

function getByUserId(req, res, next) {
    tenderVendorService
        .getByUserId(req.params.userId)
        .then((result) => res.json(result))
        .catch(next);
}
