const express = require('express');
const router = express.Router();
const path = require('path');
const fs = require('fs');
const multer = require('multer');

const pool = require('../db');
const verifyClientToken = require('../middleware/authClient');

/* ============================================================
   CONFIG
============================================================ */

const AVATAR_BASE_PATH = '/var/www/saas.gocrm.net/avatars';
const MAX_AVATAR_SIZE = 1 * 1024 * 1024; // 1MB

/* ============================================================
   MULTER STORAGE — ORG ISOLATED (MATCHES uploads.js PATTERN)
============================================================ */

const avatarStorage = multer.diskStorage({

  destination: (req, file, cb) => {

    const orgId = req.user?.organizationId;

    if (!orgId) {
      return cb(new Error('Organization ID missing for avatar upload'));
    }

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

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

    cb(null, uploadDir);
  },

  filename: (req, file, cb) => {

    const userId = req.user?.userId;

    if (!userId) {
      return cb(new Error('User ID missing for avatar upload'));
    }

    const ext = path.extname(file.originalname).toLowerCase();

    const safeName =
      `avatar_${userId}_${Date.now()}_${Math.random()
        .toString(36)
        .slice(2)}${ext}`;

    cb(null, safeName);
  }

});

/* ============================================================
   MULTER INSTANCE
============================================================ */

const avatarUpload = multer({
  storage: avatarStorage,
  limits: { fileSize: MAX_AVATAR_SIZE },
  fileFilter: (req, file, cb) => {

    const allowed = [
      'image/jpeg',
      'image/png',
      'image/webp'
    ];

    if (allowed.includes(file.mimetype)) {
      cb(null, true);
    } else {
      cb(new Error('Invalid avatar file type'));
    }
  }
});

/* ============================================================
   POST /api/avatars
   Upload / Replace Avatar
============================================================ */

router.post(
  '/',
  verifyClientToken,          // MUST run first
  avatarUpload.single('file'),
  async (req, res) => {

        console.log('AVATAR FILE OBJECT:', req.file);


    try {

      const { userId, organizationId } = req.user;

      if (!req.file) {
        return res.status(400).json({
          success: false,
          error: 'No file uploaded'
        });
      }

      const newAvatarPath =
        `/avatars/org_${organizationId}/${req.file.filename}`;

      /* --------------------------------
         Fetch Old Avatar
      -------------------------------- */

      const [[user]] = await pool.query(
        'SELECT avatar FROM users WHERE id = ?',
        [userId]
      );

      const oldAvatar = user?.avatar;

      /* --------------------------------
         Delete Old Avatar (Safe)
      -------------------------------- */

      if (
        oldAvatar &&
        oldAvatar.startsWith(`/avatars/org_${organizationId}/`)
      ) {

        const oldFilePath = path.join(
          AVATAR_BASE_PATH,
          oldAvatar.replace('/avatars/', '')
        );

        if (fs.existsSync(oldFilePath)) {
          await fs.promises.unlink(oldFilePath);
        }
      }

      /* --------------------------------
         Update DB
      -------------------------------- */
const [[dbInfo]] = await pool.query('SELECT DATABASE() AS db');
console.log('AVATAR ROUTE DB:', dbInfo.db);

      const [updateResult] = await pool.query(
  'UPDATE users SET avatar = ? WHERE id = ?',
  [newAvatarPath, userId]
);

console.log('AVATAR UPDATE RESULT:', updateResult);

const [[verifyRow]] = await pool.query(
  'SELECT avatar FROM users WHERE id = ?',
  [userId]
);

console.log('AVATAR AFTER UPDATE:', verifyRow);


      /* --------------------------------
         Success Response
      -------------------------------- */

      return res.json({
        success: true,
        avatar: newAvatarPath,
        userId
      });

    } catch (err) {

      console.error('AVATAR UPLOAD ERROR:', err);

      return res.status(500).json({
        success: false,
        error: 'Failed to upload avatar'
      });
    }
  }
);

module.exports = router;
