<?php

namespace App\Models;

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

class UserApiKey extends Model
{

    protected $fillable = [
        'user_id', 'key', 'name', 'rate_limit_per_minute', 'is_active', 'expires_at'
    ];

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

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

    public function apiCallLogs()
    {
        return $this->hasMany(ApiCallLog::class);
    }

    // Helper to generate key
    public static function generateForUser($user, $name = 'Default Key')
    {
        return self::create([
            'user_id' => $user->id,
            'key' => Str::random(40),
            'name' => $name,
            'rate_limit_per_minute' => 60,
            'is_active' => true,
        ]);
    }

   /* protected $fillable = ['user_id', 'key', 'name', 'is_active'];

    public static function createApiKey($user)
    {
        $key = Str::random(40);
        UserApiKey::create([
            'user_id' => $user->id,
            'key' => $key,
            'name' => 'My App Key',
        ]);
    }*/
}
