<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Support\Facades\Crypt;

class SecureCredential extends Model
{
    use HasFactory;

    protected $fillable = [
        'client_id',
        'platform',
        'credential_type',
        'name',
        'encrypted_payload',
        'expires_at',
        'last_checked_at',
        'last_error',
        'is_active',
        'created_by',
        'updated_by',
    ];

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

    public function setSecretPayload(array $payload): void
    {
        $this->encrypted_payload = Crypt::encryptString(json_encode($payload, JSON_THROW_ON_ERROR | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
    }

    public function getSecretPayload(): array
    {
        if (empty($this->encrypted_payload)) {
            return [];
        }

        return json_decode(Crypt::decryptString($this->encrypted_payload), true, 512, JSON_THROW_ON_ERROR) ?: [];
    }

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

    public function platformConnections(): HasMany
    {
        return $this->hasMany(PlatformConnection::class);
    }
}
