<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Support\Str;

class ApiKey extends Model
{
    use HasFactory;

    protected $fillable = [
        'tenant_id',
        'user_id',
        'name',
        'key_hash',
        'key_prefix',
        'is_active',
        'usage_count',
        'last_used_at',
        'expires_at',
    ];

    protected $hidden = ['key_hash'];

    protected $casts = [
        'is_active'    => 'boolean',
        'last_used_at' => 'datetime',
        'expires_at'   => 'datetime',
    ];

    // ── Relations ──────────────────────────────────────────────────────────

    public function tenant(): BelongsTo
    {
        return $this->belongsTo(Tenant::class);
    }

    public function user(): BelongsTo
    {
        return $this->belongsTo(User::class);
    }

    // ── Static helpers ─────────────────────────────────────────────────────

    /**
     * Generate a new API key. Returns [plaintext, prefix, hash].
     */
    public static function generateKey(): array
    {
        $key    = 'nxp_' . Str::random(48);
        $prefix = substr($key, 0, 12);
        $hash   = hash('sha256', $key);
        return [$key, $prefix, $hash];
    }

    /**
     * Find by plaintext key.
     */
    public static function findByKey(string $key): ?self
    {
        $hash = hash('sha256', $key);
        return self::where('key_hash', $hash)
            ->where('is_active', true)
            ->where(function ($q) {
                $q->whereNull('expires_at')->orWhere('expires_at', '>', now());
            })
            ->first();
    }
}
