<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Support\Facades\Crypt;
use Throwable;

final class EInvoiceConfiguration extends Model
{
    protected $table = 'einvoice_configurations';

    protected $fillable = [
        'company_id', 'provider_name', 'environment', 'encrypted_credentials',
        'electronic_address', 'electronic_address_scheme', 'is_active',
        'production_enabled', 'last_tested_at', 'connection_status',
    ];

    protected $hidden = ['encrypted_credentials'];

    protected function casts(): array
    {
        return [
            'is_active' => 'boolean',
            'production_enabled' => 'boolean',
            'last_tested_at' => 'datetime',
        ];
    }

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

    public function setCredentials(array $credentials): void
    {
        $this->encrypted_credentials = Crypt::encryptString(json_encode($credentials, JSON_THROW_ON_ERROR));
    }

    public function credentials(): array
    {
        if (! $this->encrypted_credentials) {
            return [];
        }

        try {
            return json_decode(Crypt::decryptString($this->encrypted_credentials), true, flags: JSON_THROW_ON_ERROR);
        } catch (Throwable) {
            return [];
        }
    }
}
