<?php

namespace App\Services\Hr;

use App\Models\DeviceToken;
use App\Models\User;
use App\Models\UserSession;
use App\Services\SessionInvalidator;
use App\Services\UserSessionService;

class EmployeeAccessRevocationService
{
    public function __construct(
        protected UserSessionService $sessions,
        protected SessionInvalidator $sessionInvalidator
    ) {}

    /**
     * If last working day is already over, deactivate and revoke access.
     */
    public function deactivateIfLastWorkingDatePassed(User $user): bool
    {
        if (! $user->hasPassedLastWorkingDate()) {
            return false;
        }

        $this->deactivateAndRevoke($user);

        return true;
    }

    /**
     * Deactivate the account and revoke web/API sessions so the employee cannot keep using the system.
     */
    public function deactivateAndRevoke(User $user): void
    {
        if ($user->status !== User::STATUS_INACTIVE) {
            $user->forceFill(['status' => User::STATUS_INACTIVE])->save();
        }

        if (method_exists($user, 'tokens')) {
            $user->tokens()->delete();
        }

        DeviceToken::query()->where('user_id', $user->id)->delete();

        UserSession::query()
            ->where('user_id', $user->id)
            ->get()
            ->each(fn (UserSession $session) => $this->sessions->revoke($session));

        $this->sessionInvalidator->invalidateAllForUser((int) $user->id);
    }
}
