const express = require('express');
const { createPostValidationRules, createPost, getUserPosts, getUserPostsWeb } = require('../../../controllers/application/posts/postController');
const { toggleLike } = require('../../../controllers/application/posts/likeController');
const blockCheck = require('../../../middlewares/blockCheck');
const auth = require('../../../middlewares/auth');
const isHalfRegister = require('../../../middlewares/isHalfRegister');
const path = require('path');
const fs = require('fs');
const multer = require('multer');

console.log('DEBUG: Starting to load routes/posts.js');

const ensureDir = (dir) => {
  console.log('DEBUG: Ensuring directory exists:', dir);
  if (!fs.existsSync(dir)) {
    console.log('DEBUG: Directory does not exist, creating:', dir);
    fs.mkdirSync(dir, { recursive: true });
  } else {
    console.log('DEBUG: Directory already exists:', dir);
  }
};

const imageDir = path.join(__dirname, '../../../storage/posts/images');
const videoDir = path.join(__dirname, '../../../storage/posts/videos');
console.log('DEBUG: imageDir path:', imageDir);
console.log('DEBUG: videoDir path:', videoDir);
ensureDir(imageDir);
ensureDir(videoDir);

console.log('DEBUG: Setting up multer storage');

const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    const dir = file.mimetype.startsWith('video/') ? videoDir : imageDir;
    console.log('DEBUG: multer destination for file', file.originalname, ':', dir);
    cb(null, dir);
  },
  filename: (req, file, cb) => {
    const filename = `${Date.now()}-${file.originalname}`;
    console.log('DEBUG: Generated filename for', file.originalname, ':', filename);
    cb(null, filename);
  },
});

console.log('DEBUG: Setting up multer instance with limits and filter');

const upload = multer({
  storage,
  limits: {
    fileSize: 100 * 1024 * 1024, // حداکثر 100MB
    files: 10, // حداکثر 10 فایل
    fieldSize: 1024 * 1024,
    fieldNameSize: 100,
  },
  fileFilter: (req, file, cb) => {
    console.log('DEBUG: Checking file filter for', file.originalname, 'mimetype:', file.mimetype);
    if (file.mimetype.startsWith('image/') || file.mimetype.startsWith('video/')) {
      console.log('DEBUG: File accepted:', file.originalname);
      cb(null, true);
    } else {
      console.log('DEBUG: File rejected:', file.originalname);
      cb(new Error('فقط تصاویر یا ویدئوها مجاز هستند'), false);
    }
  },
}).array('post_files', 10);

const multerErrorHandler = (err, req, res, next) => {
  console.log('DEBUG: Request headers:', JSON.stringify(req.headers, null, 2));
  console.log('DEBUG: Request body (raw):', req.body);
  console.log('DEBUG: Request files:', req.files || 'No files received');
  if (err instanceof multer.MulterError) {
    console.error('DEBUG: Multer error:', err.message, err.code, err.field);
    return res.status(400).json({
      error: true,
      message: `خطای آپلود: ${err.message} (${err.code})`,
      field: err.field,
    });
  } else if (err) {
    console.error('DEBUG: File filter error:', err.message);
    return res.status(400).json({
      error: true,
      message: err.message,
    });
  }
  console.log('DEBUG: Multer processing completed, files:', req.files || 'No files');
  console.log('DEBUG: Request body after multer:', req.body);
  next();
};

console.log('DEBUG: Setting up express router');

const router = express.Router();

// روت اصلی با multipart/form-data
router.post(
  '/create',
  (req, res, next) => {
    console.log('DEBUG: reached auth');
    console.log('DEBUG: Raw request headers:', JSON.stringify(req.headers, null, 2));
    next();
  },
  auth,
  (req, res, next) => {
    console.log('DEBUG: reached blockCheck');
    next();
  },
  blockCheck,
  (req, res, next) => {
    console.log('DEBUG: reached isHalfRegister');
    next();
  },
  isHalfRegister,
  (req, res, next) => {
    console.log('DEBUG: reached multer');
    console.log('DEBUG: Content-Length:', req.headers['content-length']);
    console.log('DEBUG: Content-Type:', req.headers['content-type']);
    next();
  },
  upload,
  multerErrorHandler,
  (req, res, next) => {
    console.log('DEBUG: reached validation');
    console.log('DEBUG: Parsed files:', req.files || 'No files');
    console.log('DEBUG: Parsed body:', req.body);
    next();
  },
  createPostValidationRules(),
  (req, res, next) => {
    console.log('DEBUG: reached controller');
    next();
  },
  createPost
);

// روت جدید برای Base64
router.post(
  '/create-base64',
  (req, res, next) => {
    console.log('DEBUG: reached auth for base64');
    console.log('DEBUG: Raw request headers:', JSON.stringify(req.headers, null, 2));
    next();
  },
  auth,
  (req, res, next) => {
    console.log('DEBUG: reached blockCheck for base64');
    next();
  },
  blockCheck,
  (req, res, next) => {
    console.log('DEBUG: reached isHalfRegister for base64');
    next();
  },
  isHalfRegister,
  (req, res, next) => {
    console.log('DEBUG: Request body (base64):', JSON.stringify(req.body, null, 2));
    next();
  },
  createPostValidationRules(),
  async (req, res) => {
    try {
      const { files, caption } = req.body;
      console.log('DEBUG: Received files (base64):', files.length);
      console.log('DEBUG: Received caption:', caption);

      // تبدیل Base64 به فایل
      const savedFiles = await Promise.all(
        files.map(async (file, index) => {
          const buffer = Buffer.from(file.data.split(',')[1], 'base64');
          const dir = file.type.startsWith('video/') ? videoDir : imageDir;
          const filename = `${Date.now()}-${index}-${file.name}`;
          const filePath = path.join(dir, filename);
          console.log('DEBUG: Saving file:', filePath);
          await fs.promises.writeFile(filePath, buffer);
          return {
            path: filePath,
            filename,
            mimetype: file.type,
          };
        })
      );

      // فراخوانی createPost با فرمت مشابه
      req.files = savedFiles;
      req.body = { caption };
      console.log('DEBUG: Prepared files for createPost:', savedFiles);
      console.log('DEBUG: Prepared body for createPost:', req.body);
      await createPost(req, res);
    } catch (err) {
      console.error('DEBUG: Base64 processing error:', err.message);
      res.status(400).json({
        error: true,
        message: `خطای پردازش فایل‌ها: ${err.message}`,
      });
    }
  }
);

router.post('/like', [auth, blockCheck], toggleLike);
router.get('/user-posts', [auth], getUserPosts);
router.get('/user-posts/web', getUserPostsWeb);

console.log('DEBUG: Finished loading routes/posts.js');

module.exports = router;