<?php

namespace App\Models;

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

class ClientApiKey extends Model
{
    protected $fillable = [
        'client_name',
        'api_key',
        'api_secret',
        'allowed_origins',
        'is_active',
        'feature_cyber_security',
        'feature_cloud_storage',
        'feature_full_email_setup',
        'feature_full_management_system',
        'email_accounts_used',
        'email_accounts_limit',
    ];

    protected $hidden = ['api_secret'];

    protected $casts = [
        'is_active' => 'boolean',
        'feature_cyber_security' => 'boolean',
        'feature_cloud_storage' => 'boolean',
        'feature_full_email_setup' => 'boolean',
        'feature_full_management_system' => 'boolean',
        'email_accounts_used' => 'integer',
        'email_accounts_limit' => 'integer',
    ];

    public static function generate(string $clientName, ?string $allowedOrigins = null, array $attributes = []): self
    {
        return self::create([
            'client_name' => $clientName,
            'api_key' => 'ck_' . Str::random(61),
            'api_secret' => 'cs_' . Str::random(61),
            'allowed_origins' => $allowedOrigins,
            'feature_cyber_security' => (bool) ($attributes['feature_cyber_security'] ?? false),
            'feature_cloud_storage' => (bool) ($attributes['feature_cloud_storage'] ?? false),
            'feature_full_email_setup' => (bool) ($attributes['feature_full_email_setup'] ?? false),
            'feature_full_management_system' => (bool) ($attributes['feature_full_management_system'] ?? false),
            'email_accounts_used' => (int) ($attributes['email_accounts_used'] ?? 5),
            'email_accounts_limit' => max(1, (int) ($attributes['email_accounts_limit'] ?? 20)),
        ]);
    }

    public function serviceFeatures(): array
    {
        return [
            'cyber_security' => (bool) $this->feature_cyber_security,
            'cloud_storage' => (bool) $this->feature_cloud_storage,
            'full_email_setup' => (bool) $this->feature_full_email_setup,
            'full_management_system' => (bool) $this->feature_full_management_system,
            'email_accounts_used' => (int) ($this->email_accounts_used ?? 0),
            'email_accounts_limit' => (int) ($this->email_accounts_limit ?? 20),
        ];
    }
}
