import multer from "multer";
import path from "path";
import fs from "fs";
import { fileURLToPath } from "url";
import logger from "../utils/logger.js";

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);

// Create uploads directory if it doesn't exist
const uploadsDir = path.join(__dirname, "../../uploads/projects");
if (!fs.existsSync(uploadsDir)) {
  fs.mkdirSync(uploadsDir, { recursive: true });
}

// Configure storage
const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, uploadsDir);
  },
  filename: (req, file, cb) => {
    // Generate unique filename: timestamp-random-originalname
    const uniqueSuffix = `${Date.now()}-${Math.round(Math.random() * 1e9)}`;
    const ext = path.extname(file.originalname);
    const filename = `${uniqueSuffix}${ext}`;
    cb(null, filename);
  },
});

// File filter - only allow images
const fileFilter = (req, file, cb) => {
  // Check file type
  const allowedMimes = ["image/jpeg", "image/jpg", "image/png", "image/webp"];

  if (allowedMimes.includes(file.mimetype)) {
    cb(null, true);
  } else {
    cb(
      new Error(
        "Invalid file type. Only JPEG, JPG, PNG, and WEBP images are allowed."
      ),
      false
    );
  }
};

// Configure multer
const upload = multer({
  storage: storage,
  fileFilter: fileFilter,
  limits: {
    fileSize: 10 * 1024 * 1024, // 10MB limit per file
    files: 10, // Maximum 10 files
  },
});

// Middleware for multiple image uploads with error handling
export const uploadProjectImages = (req, res, next) => {
  upload.array("images", 10)(req, res, (err) => {
    if (err) {
      // Handle multer errors
      if (err.name === "MulterError") {
        if (err.code === "LIMIT_FILE_SIZE") {
          return res.status(400).json({
            success: false,
            error: "File size too large. Maximum 10MB per file allowed.",
          });
        }
        if (err.code === "LIMIT_FILE_COUNT") {
          return res.status(400).json({
            success: false,
            error: "Too many files. Maximum 10 images allowed per project.",
          });
        }
        if (err.code === "LIMIT_UNEXPECTED_FILE") {
          return res.status(400).json({
            success: false,
            error: "Unexpected file field. Use 'images' field name.",
          });
        }
      }

      // Handle other upload errors (file type, etc.)
      return res.status(400).json({
        success: false,
        error: err.message || "File upload error",
      });
    }
    next();
  });
};

// Helper function to get base URL from environment or request
const getBaseUrl = (req = null) => {
  // Priority: API_URL > BASE_URL > construct from request > default
  if (process.env.API_URL) {
    return process.env.API_URL.replace(/\/$/, ""); // Remove trailing slash
  }

  if (process.env.BASE_URL) {
    return process.env.BASE_URL.replace(/\/$/, ""); // Remove trailing slash
  }

  // If request is available, construct from request
  if (req) {
    const protocol = req.protocol || "http";
    const host = req.get("host") || "localhost:3000";
    return `${protocol}://${host}`;
  }

  // Default fallback
  const port = process.env.PORT || 3000;
  return `http://localhost:${port}`;
};

// Helper function to get file URL with full path
export const getFileUrl = (filename, req = null) => {
  if (!filename) return "";

  const baseUrl = getBaseUrl(req);
  return `${baseUrl}/uploads/projects/${filename}`;
};

// Helper function to transform image URLs to full URLs (for existing projects)
export const transformImageUrls = (images, req = null) => {
  if (!images || !Array.isArray(images)) return images;

  const baseUrl = getBaseUrl(req);

  return images.map((image) => {
    // If URL is already a full URL, return as is
    if (
      image.url &&
      (image.url.startsWith("http://") || image.url.startsWith("https://"))
    ) {
      return image;
    }

    // If URL is relative, convert to full URL
    if (image.url && image.url.startsWith("/")) {
      return {
        ...image,
        url: `${baseUrl}${image.url}`,
      };
    }

    // If only filename exists, construct full URL
    if (image.filename) {
      return {
        ...image,
        url: `${baseUrl}/uploads/projects/${image.filename}`,
      };
    }

    return image;
  });
};

// Helper function to delete file
export const deleteFile = (filename) => {
  if (!filename) return;

  try {
    const filePath = path.join(uploadsDir, filename);
    if (fs.existsSync(filePath)) {
      fs.unlinkSync(filePath);
    }
  } catch (error) {
    logger.error(`Failed to delete file: ${filename}`, error);
    throw error;
  }
};

// Helper function to delete multiple files
export const deleteFiles = (filenames) => {
  if (!Array.isArray(filenames)) return;

  filenames.forEach((filename) => {
    try {
      deleteFile(filename);
    } catch (error) {
      logger.error(`Failed to delete file: ${filename}`, error);
    }
  });
};
