// routes/userInfo.js

import express from "express"
const router = express.Router();
import bcrypt  from 'bcryptjs'
import SettingProfile from '../models/settingProfile.js'; // adjust path if needed
import WebsiteSubmission from '../models/websiteSubmission.js';
import SubmitDirectory from '../models/submitDirectory.js';
import SubmitAiWebsite from '../models/submitAiWebsite.js';
import Favorite from '../models/favorite.js';
import Vote from '../models/vote.js';

import {User} from "../models/user.js"

import { authenticate } from '../middleware/authMiddleware.js';

// 🔒 Middleware to prevent caching of user info responses
const noCacheMiddleware = (req, res, next) => {
  res.set({
    'Cache-Control': 'no-store, no-cache, must-revalidate, private, max-age=0',
    'Pragma': 'no-cache',
    'Expires': '0',
    'Vary': 'Authorization'
  });
  next();
};

// Apply no-cache to all user info routes
router.use(noCacheMiddleware);

// Get current user
router.get('/me', authenticate, async (req, res) => {
    try {
        const user = await User.findById(req.user.id).select('-passwordHash');
        res.json(user);
    } catch (error) {
        res.status(500).json({ message: 'Server error' });
    }
});

// Change password
router.put('/change-password', authenticate, async (req, res) => {
    try {
        const { currentPassword, newPassword } = req.body;
        const user = await User.findById(req.user.id);

        // Check if user has password (not social login)
        if (user.isSocialLogin) {
            return res.status(400).json({ message: 'Social login users cannot change password' });
        }

        // Verify current password
        const isMatch = await bcrypt.compare(currentPassword, user.passwordHash);
        if (!isMatch) {
            return res.status(400).json({ message: 'Current password is incorrect' });
        }

        // Hash new password
        const salt = await bcrypt.genSalt(10);
        user.passwordHash = await bcrypt.hash(newPassword, salt);

        await user.save();
        res.json({ message: 'Password updated successfully' });
    } catch (error) {
        res.status(500).json({ message: 'Server error' });
    }
});

// Change email
router.put('/change-email', authenticate, async (req, res) => {
    try {
        const { newEmail } = req.body;
        const user = await User.findById(req.user.id);

        // Check if user has password (not social login)
        if (user.isSocialLogin) {
            return res.status(400).json({ message: 'Social login users cannot change email' });
        }

        // Check if email already exists
        const existingUser = await User.findOne({ email: newEmail });
        if (existingUser) {
            return res.status(400).json({ message: 'Email already in use' });
        }

        user.email = newEmail;
        await user.save();

        res.json({ message: 'Email updated successfully' });
    } catch (error) {
        res.status(500).json({ message: 'Server error' });
    }
});

// Delete account


router.delete('/delete-account', authenticate, async (req, res) => {
  try {
    const { password } = req.body;
    const user = await User.findById(req.user.id);

    if (!user) {
      return res.status(404).json({ message: 'User not found' });
    }

    // For normal email/password users, verify password
    if (!user.isSocialLogin) {
      const isMatch = await bcrypt.compare(password, user.passwordHash);
      if (!isMatch) {
        return res.status(400).json({ message: 'Password is incorrect' });
      }
    }

    // 🗑️ Delete all user's data
    console.log(`Deleting account for user: ${req.user.id}`);
    
    // Delete associated SettingProfile
    await SettingProfile.findOneAndDelete({ submittedBy: req.user.id });
    console.log('✅ Deleted user profile settings');

    // Delete all website submissions
    await WebsiteSubmission.deleteMany({ submittedBy: req.user.id });
    console.log('✅ Deleted website submissions');

    // Delete all directory submissions
    await SubmitDirectory.deleteMany({ submittedBy: req.user.id });
    console.log('✅ Deleted directory submissions');

    // Delete all AI website submissions
    await SubmitAiWebsite.deleteMany({ submittedBy: req.user.id });
    console.log('✅ Deleted AI website submissions');

    // Delete all favorites
    await Favorite.deleteMany({ userId: req.user.id });
    console.log('✅ Deleted user favorites');

    // Delete all votes
    await Vote.deleteMany({ userId: req.user.id });
    console.log('✅ Deleted user votes');

    // 🗑️ Finally, delete the user account
    await User.findByIdAndDelete(req.user.id);
    console.log('✅ Deleted user account');

    // ✅ Send confirmation
    res.json({ 
      message: 'Account and all associated data deleted successfully',
      deletedData: {
        profile: true,
        websites: true,
        directories: true,
        aiWebsites: true,
        favorites: true,
        votes: true,
        account: true
      }
    });

  } catch (error) {
    console.error('Error deleting account:', error);
    res.status(500).json({ message: 'Server error during account deletion' });
  }
});


export default router;