const path = require("path");
const fs = require("fs");
const { setResponse } = require("../helpers/utils");
const {
  createFileUploadDb,
  deleteFileUploadByPathDb,
} = require("../db/file_uploads.db");

const uploadFile = async (req, res) => {
  try {
    if (!req.file) {
      const response = await setResponse([], "Tidak ada file yang diunggah", 400);
      return res.status(400).json(response);
    }

    const file = req.file;
    const ext = path.extname(file.originalname).toLowerCase();
    const typeDoc = ext === ".pdf" ? "PDF" : "IMAGE";
    const folder = typeDoc === "PDF" ? "pdf" : "images";

    const pathDocument = `${folder}/${file.filename}`;

    const fileData = {
      file_upload_name: file.originalname,
      path_document: pathDocument,
      type_document: typeDoc,
      createdBy: req.user?.user_id || null,
    };

    await createFileUploadDb(fileData);

    const response = await setResponse(
      {
        file_upload_name: file.originalname,
        path_document: pathDocument,
        path_solution: pathDocument
      },
      "File berhasil diunggah"
    );
    res.status(200).json(response);
  } catch (error) {
    const response = await setResponse([], error.message, 500);
    res.status(500).json(response);
  }
};




const getFileByPath = async (req, res) => {
  try {
    const { folder, filename } = req.params;

    // Decode filename from URL encoding
    const decodedFilename = decodeURIComponent(filename);
    const filePath = path.join(__dirname, "../uploads", folder, decodedFilename);

    console.log('getFileByPath Debug:', {
      folder,
      originalFilename: filename,
      decodedFilename,
      filePath
    });

    if (!fs.existsSync(filePath)) {
      console.log('File not found at path:', filePath);

      // try {
      //   const folderPath = path.join(__dirname, "../uploads", folder);
      //   const availableFiles = fs.readdirSync(folderPath);
      //   console.log('Available files in', folderPath, ':', availableFiles);
      // } catch (listError) {
      //   console.log('Could not list files in folder:', listError.message);
      // }

      const response = await setResponse([], "File tidak ditemukan", 404);
      return res.status(404).json(response);
    }

    res.sendFile(filePath);
  } catch (error) {
    console.error('getFileByPath Error:', error);
    const response = await setResponse([], error.message, 500);
    res.status(500).json(response);
  }
};

const deleteFileByPath = async (req, res) => {
  try {
    const { folder, filename } = req.params;

    // Decode filename from URL encoding
    const decodedFilename = decodeURIComponent(filename);
    const filePath = path.join(__dirname, "../uploads", folder, decodedFilename);

    if (!fs.existsSync(filePath)) {
      const response = await setResponse([], "File tidak ditemukan", 404);
      return res.status(404).json(response);
    }

    // Delete physical file
    fs.unlinkSync(filePath);

    const pathDocument = `${folder}/${decodedFilename}`;
    const deletedBy = req.user?.user_id || null;
    await deleteFileUploadByPathDb(pathDocument, deletedBy);

    const response = await setResponse([], "File berhasil dihapus");
    res.status(200).json(response);
  } catch (error) {
    const response = await setResponse([], error.message, 500);
    res.status(500).json(response);
  }
};

module.exports = {
  uploadFile,
  getFileByPath,
  deleteFileByPath,
};