const express = require('express');
const path = require('path');
const fs = require('fs');
const multer = require('multer');

const verifyClientToken = require('../middleware/authClient');
const { isAllowedFileType } = require('../utils/fileTypes');

const router = express.Router();

/* ======================================================
   MULTER STORAGE — ORG ISOLATED
====================================================== */
const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    const orgId = req.user.organizationId;

    const uploadDir = path.join(
      __dirname,
      '..',
      'uploads',
      `org_${orgId}`
    );

    if (!fs.existsSync(uploadDir)) {
      fs.mkdirSync(uploadDir, { recursive: true });
    }

    cb(null, uploadDir);
  },

  filename: (req, file, cb) => {
    const ext = path.extname(file.originalname);
    const safeName =
      `file_${Date.now()}_${Math.random().toString(36).slice(2)}${ext}`;
    cb(null, safeName);
  }
});

const upload = multer({
  storage,
  limits: { fileSize: 50 * 1024 * 1024 }
});

/* ======================================================
   EXPORT ROUTER
====================================================== */
module.exports = ({ pool, io }) => {

  router.post(
    '/',
    verifyClientToken,
    upload.single('file'),
    async (req, res) => {
      try {

        const senderId = req.user.userId;
        const organizationId = req.user.organizationId;

        const { receiverId, projectId, roomId = 0 } = req.body;

        const file = req.file;

        if (!file) {
          return res.status(400).json({ success: false, message: 'File missing' });
        }

        if (!isAllowedFileType(file.mimetype)) {
          return res.status(400).json({ success: false, message: 'File type not allowed' });
        }

        /* -------------------------
           URL BUILD
        -------------------------- */
        const protocol = req.headers['x-forwarded-proto'] || req.protocol;
        const host = req.get('host');
        const baseUrl = process.env.BASE_URL || `${protocol}://${host}`;

        const publicPath =
          `/uploads/org_${organizationId}/${path.basename(file.path)}`;

        const fileUrl = `${baseUrl}${publicPath}`;

        const filename = file.originalname;

        /* ======================================================
           PROJECT ROOM FILE MESSAGE
        ====================================================== */
        if (projectId) {

          const [msgResult] = await pool.query(
            `
            INSERT INTO project_room_messages
            (organizationId, projectId, roomId, sender_id, message, is_file, filename)
            VALUES (?, ?, ?, ?, '', 1, ?)
            `,
            [
              organizationId,
              projectId,
              roomId,
              senderId,
              filename
            ]
          );

          const projectMessageId = msgResult.insertId;

          await pool.query(
            `
            INSERT INTO files
            (organizationId, sender_id, filename, filepath, project_message_id)
            VALUES (?, ?, ?, ?, ?)
            `,
            [
              organizationId,
              senderId,
              filename,
              publicPath,
              projectMessageId
            ]
          );

          const chatMessage = {
            id: projectMessageId,
            organizationId,
            projectId,
            roomId,
            senderId,

            isFile: true,
            filename,
            fileUrl,

            message: '',
            timestamp: Date.now()
          };

          io.to(`project:${projectId}:room:${roomId}`)
            .emit('receive_message', chatMessage);

          return res.json({ success: true, file: chatMessage });
        }

        /* ======================================================
           DIRECT USER FILE MESSAGE
        ====================================================== */
        if (!receiverId) {
          return res.status(400).json({
            success: false,
            message: 'receiverId required for direct chat file'
          });
        }

        const [msgResult] = await pool.query(
          `
          INSERT INTO messages
          (organizationId, sender_id, receiver_id, message, is_file, filename)
          VALUES (?, ?, ?, '', 1, ?)
          `,
          [
            organizationId,
            senderId,
            receiverId,
            filename
          ]
        );

        const messageId = msgResult.insertId;

        await pool.query(
          `
          INSERT INTO files
          (organizationId, sender_id, receiver_id, filename, filepath, message_id)
          VALUES (?, ?, ?, ?, ?, ?)
          `,
          [
            organizationId,
            senderId,
            receiverId,
            filename,
            publicPath,
            messageId
          ]
        );

        const chatMessage = {
          id: messageId,
          organizationId,
          senderId,
          receiverId,

          isFile: true,
          filename,
          fileUrl,

          message: '',
          timestamp: Date.now()
        };

        io.to(`org:${organizationId}`)
          .emit('receive_message', chatMessage);

        return res.json({ success: true, file: chatMessage });

      } catch (err) {
        console.error('UPLOAD FAILED:', err);
        return res.status(500).json({
          success: false,
          message: 'Upload failed'
        });
      }
    }
  );

  return router;
};
