<?php

namespace App\Casts;

use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Crypt;

/**
 * Cast transitorio para arrays JSON que passam a ser encriptados.
 * Tenta decriptar; se falhar, assume que e JSON plaintext.
 *
 * Substituir por 'encrypted:array' nativo apos migracao completa.
 */
class TransitionalEncryptedArray implements CastsAttributes
{
    public function get(Model $model, string $key, mixed $value, array $attributes): ?array
    {
        if ($value === null) {
            return null;
        }

        try {
            $decrypted = Crypt::decryptString($value);
            return json_decode($decrypted, true);
        } catch (\Illuminate\Contracts\Encryption\DecryptException) {
            // Valor ainda em JSON plaintext (pre-migracao)
            return json_decode($value, true);
        }
    }

    public function set(Model $model, string $key, mixed $value, array $attributes): ?string
    {
        if ($value === null) {
            return null;
        }

        return Crypt::encryptString(json_encode($value));
    }
}
