<?php

declare(strict_types=1);

namespace App\Models\Market;

use App\Models\Model;
use App\Models\User;

/**
 * @property int $id
 * @property string $hashkey
 * @property string $access_key
 * @property int $store_id
 * @property string $name
 * @property string $status
 * @property string $last_used_at
 * @property int $created_by
 * @property \Carbon\Carbon $created_at
 * @property \Carbon\Carbon $updated_at
 */
class PosAccessKey extends Model
{
    /**
     * The table associated with the model.
     */
    protected ?string $table = 'pos_access_keys';

    /**
     * The attributes that are mass assignable.
     */
    protected array $fillable = [
        'hashkey',
        'access_key',
        'store_id',
        'name',
        'status',
        'is_active',
        'expires_at',
        'last_used_at',
        'created_by',
        'updated_by',
    ];

    /**
     * The attributes that should be cast to native types.
     */
    protected array $casts = [
        'id' => 'integer',
        'store_id' => 'integer',
        'created_by' => 'integer',
        'updated_by' => 'integer',
        'is_active' => 'boolean',
        'expires_at' => 'datetime',
    ];

    /**
     * Check if this access key is expired.
     */
    public function isExpired(): bool
    {
        return $this->expires_at !== null && $this->expires_at->isPast();
    }

    /**
     * Auto-expire: set all expired active keys to inactive.
     * Call this before listing or validating keys.
     */
    public static function autoExpire(): void
    {
        self::where('status', 'active')
            ->whereNotNull('expires_at')
            ->where('expires_at', '<', now())
            ->update(['status' => 'inactive']);
    }

    /**
     * Relationships
     */
    public function store()
    {
        return $this->belongsTo(Store::class, 'store_id');
    }

    public function creator()
    {
        return $this->belongsTo(User::class, 'created_by');
    }
}
