<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class ApiKey extends Model
{
    use HasFactory;

    /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */
    protected $fillable = [
        'user_id',
        'platform',
        'name',
        'key',
        'scopes',
        'is_active',
        'expires_at',
    ];

    /**
     * Get the attributes that should be cast.
     *
     * @return array<string, string>
     */
    protected function casts(): array
    {
        return [
            'scopes' => 'array',
            'is_active' => 'boolean',
            'expires_at' => 'datetime',
        ];
    }

    /**
     * Get the user that owns the API key.
     */
    public function user()
    {
        return $this->belongsTo(User::class);
    }

    /**
     * Get the API logs for this key.
     */
    public function apiLogs()
    {
        return $this->hasMany(ApiLog::class, 'api_key', 'key');
    }

    /**
     * Check if the API key is valid (active and not expired).
     */
    public function isValid(): bool
    {
        if (!$this->is_active) {
            return false;
        }

        if ($this->expires_at && $this->expires_at->isPast()) {
            return false;
        }

        return true;
    }

    /**
     * Platform constants
     */
    const PLATFORM_ANDROID = 1;
    const PLATFORM_IOS = 2;
    const PLATFORM_WEB = 3;
    const PLATFORM_PARTNER = 4;

    /**
     * Get platform options
     */
    public static function getPlatformOptions(): array
    {
        return [
            self::PLATFORM_ANDROID => 'Android',
            self::PLATFORM_IOS => 'iOS',
            self::PLATFORM_WEB => 'Web',
            self::PLATFORM_PARTNER => 'Partner',
        ];
    }
}
