<?php

declare(strict_types=1);

namespace App\Models;

use App\Models\Traits\BelongsToTenant;
use Illuminate\Database\Eloquent\Concerns\HasUuids;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Support\Facades\Crypt;

/**
 * @property string $id
 * @property string $tenant_id
 * @property string $provider
 * @property string $display_name
 * @property bool $is_active
 * @property int $sort_order
 * @property string|null $credentials_encrypted
 * @property bool $sandbox_mode
 * @property array|null $meta
 */
class PaymentMethod extends Model
{
    use BelongsToTenant;
    use HasUuids;

    public const PROVIDER_KCP = 'kcp';
    public const PROVIDER_INICIS = 'inicis';
    public const PROVIDER_TOSS = 'toss';
    public const PROVIDER_KAKAOPAY = 'kakaopay';
    public const PROVIDER_STRIPE = 'stripe';

    public const PROVIDERS = [
        self::PROVIDER_KCP,
        self::PROVIDER_INICIS,
        self::PROVIDER_TOSS,
        self::PROVIDER_KAKAOPAY,
        self::PROVIDER_STRIPE,
    ];

    protected $fillable = [
        'tenant_id',
        'provider',
        'display_name',
        'is_active',
        'sort_order',
        'credentials_encrypted',
        'sandbox_mode',
        'meta',
    ];

    protected $casts = [
        'is_active' => 'boolean',
        'sandbox_mode' => 'boolean',
        'sort_order' => 'integer',
        'meta' => 'array',
    ];

    protected $hidden = [
        'credentials_encrypted',
    ];

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

    public function getCredentials(): array
    {
        if (! $this->credentials_encrypted) {
            return [];
        }
        try {
            $decoded = Crypt::decryptString($this->credentials_encrypted);
            return json_decode($decoded, true) ?? [];
        } catch (\Throwable) {
            return [];
        }
    }

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