<?php

namespace App\Commands;

use CodeIgniter\CLI\BaseCommand;
use CodeIgniter\CLI\CLI;
use Config\Database;

/**
 * Purges expired password-reset tokens and stale rate-limit rows (the DB
 * fallback used when Redis is not configured — see RateLimit filter),
 * plus orphaned temp upload files older than 24 hours.
 */
class CleanupTempFiles extends BaseCommand
{
    protected $group       = 'Scheduler';
    protected $name        = 'cleanup:temp-files';
    protected $description = 'Purges expired password resets, stale rate-limit rows, and orphaned temp files.';

    public function run(array $params)
    {
        $db = Database::connect();

        $resetsDeleted = $db->table('password_resets')->where('expires_at <', date('Y-m-d H:i:s'))->delete();
        $rateLimitsDeleted = $db->table('rate_limit_hits')->where('window_start <', date('Y-m-d H:i:s', strtotime('-1 hour')))->delete();

        $tempDir = WRITEPATH . 'uploads/tmp';
        $filesRemoved = 0;
        if (is_dir($tempDir)) {
            foreach (glob($tempDir . '/*') as $file) {
                if (is_file($file) && (time() - filemtime($file)) > 86400) {
                    unlink($file);
                    $filesRemoved++;
                }
            }
        }

        CLI::write("Cleanup complete: expired reset tokens removed, stale rate-limit rows removed, {$filesRemoved} temp file(s) removed.", 'green');
    }
}
