<?php

namespace App\Commands;

use CodeIgniter\CLI\BaseCommand;
use CodeIgniter\CLI\CLI;
use CodeIgniter\Events\Events;
use CodeIgniter\I18n\Time;

class DeleteInactiveUsers extends BaseCommand
{
    protected $group       = 'Maintenance';
    protected $name        = 'users:delete-inactive-users';
    protected $description = 'Delete users that are inactive and created more than 15 minutes ago, along with their entries in the parents table and user_roles table if applicable.';

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

        try {
            CLI::write('Running deletion of inactive users...', 'yellow');
            $cutoffTime = Time::now()->subMinutes(15)->toDateTimeString();
            CLI::write("Cutoff time for deletion: $cutoffTime", 'blue');
            log_message('debug', 'Cutoff time for deletion: ' . $cutoffTime);

            // ─────────────────────────────────────────────────────
            // 1 Fetch inactive users older than 15 min
            // ─────────────────────────────────────────────────────
            $users = $db->table('users')
                        ->select('id, firstname, lastname, email, created_at')
                        ->where('status', 'Inactive')
                        ->where('created_at <', $cutoffTime)
                        ->get()
                        ->getResultArray();

            if (empty($users)) {
                CLI::write('No inactive users found to delete.', 'yellow');
                $this->purgeOrphanedUserRoles($db);
                return;
            }

            CLI::write('Found ' . count($users) . ' users for deletion.', 'green');

            // collect IDs
            $userIds = array_column($users, 'id');

            // ─────────────────────────────────────────────────────
            // 2 Transaction: delete parents → user_roles → users
            // ─────────────────────────────────────────────────────
            $db->transStart();

            // 2-a Delete any secondary-parent rows tied to these users
            $parentsBuilder = $db->table('parents');
            $deletedParents = $parentsBuilder->whereIn('firstparent_id', $userIds)->delete();
            CLI::write("Deleted $deletedParents associated second-parent record(s).", 'blue');
            log_message('info', "Deleted $deletedParents rows from parents table.");

            // 2-b Delete user_roles rows
            $db->table('user_roles')->whereIn('user_id', $userIds)->delete();
            CLI::write('Deleted related user_roles rows.', 'blue');

            // 2-c Delete users
            $db->table('users')->whereIn('id', $userIds)->delete();
            CLI::write('Deleted users: ' . implode(', ', $userIds), 'green');

            $db->transComplete();

            if (!$db->transStatus()) {
                CLI::write('Transaction failed; rolled back.', 'red');
                return;
            }

            // Purge any stray user_role rows left behind (defensive)
            $this->purgeOrphanedUserRoles($db);

            $msg = 'Deleted ' . count($users) . " inactive users plus $deletedParents parents rows.";
            CLI::write($msg, 'green');
            log_message('info', $msg);
        } catch (\Throwable $e) {
            CLI::write('Error deleting inactive users: ' . $e->getMessage(), 'red');
            log_message('error', 'Error deleting inactive users: ' . $e->getMessage());
        }
    }

    /**
     * Remove user_roles rows that point to non-existent users.
     */
    private function purgeOrphanedUserRoles(\CodeIgniter\Database\BaseConnection $db): void
    {
        $orphaned = $db->table('user_roles')
                    ->whereNotIn('user_id', function ($q) use ($db) {
                        $q->select('id')->from('users');
                    })
                    ->delete();

        if ($orphaned) {
            CLI::write("Deleted $orphaned orphaned user_roles rows.", 'green');
            log_message('info', "Deleted $orphaned orphaned user_roles rows.");
        } else {
            CLI::write('No orphaned user_roles rows found.', 'yellow');
        }
    }


}