<?php

namespace App\Models;

use App\Enums\EarnApiTokenStatus;
use Illuminate\Database\Eloquent\SoftDeletes;
use Laravel\Sanctum\PersonalAccessToken;

class EarnApiToken extends PersonalAccessToken
{
    use SoftDeletes;

    protected $table = 'personal_access_tokens';

    protected function casts(): array
    {
        return array_merge(parent::casts(), [
            'is_active' => 'boolean', 'revoked_at' => 'datetime', 'deleted_at' => 'datetime',
            'device_bound_at' => 'datetime', 'last_seen_at' => 'datetime', 'device_mismatch_seen' => 'boolean',
        ]);
    }

    public function status(): EarnApiTokenStatus
    {
        if ($this->revoked_at !== null) {
            return EarnApiTokenStatus::Revoked;
        }
        if ($this->expires_at !== null && $this->expires_at->isPast()) {
            return EarnApiTokenStatus::Expired;
        }
        if (! $this->is_active) {
            return EarnApiTokenStatus::Inactive;
        }

        return EarnApiTokenStatus::Active;
    }

    public function canAccessTasks(): bool
    {
        return $this->status() === EarnApiTokenStatus::Active
            && $this->can('tasks:read')
            && $this->tokenable instanceof EarnMember
            && $this->tokenable->canUseApi();
    }
}
