const fs = require('fs').promises;
const path = require('path');
const { models } = require(path.join(process.env.ROOT_PATH, "./db/db"));
const { Mailbox } = models;
const { format } = require('date-fns');

async function deleteExpiredMailboxes() {
  try {
    // Format current date for database comparison using date-fns
    const now = format(new Date(), 'yyyy-MM-dd HH:mm:ss');
    
    // First, get the list of mailboxes that will be deleted
    const expiredMailboxes = await Mailbox.query()
      .where('expires', '<', now)
      .select(['username', 'domain']);
    
    console.log(`Found ${expiredMailboxes.length} expired mailboxes to delete`);
    
    // Delete the physical mailbox directories
    for (const mailbox of expiredMailboxes) {
      try {
        const mailboxPath = path.join('/var/mail', mailbox.domain, mailbox.local_part || mailbox.username.split('@')[0]);
        
        // Check if directory exists before attempting to delete
        await fs.access(mailboxPath);
        await fs.rm(mailboxPath, { recursive: true, force: true });
        
        console.log(`Deleted physical mailbox at ${mailboxPath}`);
      } catch (err) {
        // If directory doesn't exist, just log and continue
        console.log(`No physical mailbox found for ${mailbox.username}@${mailbox.domain} or error: ${err.message}`);
      }
    }
    
    // Now delete from database
    const deleted = await Mailbox.query()
      .where('expires', '<', now)
      .delete();
    
    console.log(`Deleted ${deleted} expired mailbox records from database`);
    return deleted;
  } catch (error) {
    console.error('Error deleting expired mailboxes:', error);
    throw error;
  }
}

module.exports = {
  deleteExpiredMailboxes,
};