<?php

namespace App\Models\Tenants;

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

class BarobillSetting extends Model
{
    protected $fillable = [
        'tenant_id',
        'corp_num',
        'cert_key',
        'barobill_id',
        'corp_name',
        'ceo_name',
        'addr',
        'biz_type',
        'biz_class',
        'contact_id',
        'contact_name',
        'contact_tel',
        'is_active',
        'auto_issue',
        'verified_at',
        'created_by',
        'updated_by',
    ];

    protected $casts = [
        'is_active' => 'boolean',
        'auto_issue' => 'boolean',
        'verified_at' => 'datetime',
    ];

    protected $hidden = [
        'cert_key',
    ];

    // =========================================================================
    // 암호화 처리 (cert_key)
    // =========================================================================

    /**
     * cert_key 암호화 저장
     */
    public function setCertKeyAttribute(?string $value): void
    {
        $this->attributes['cert_key'] = $value ? Crypt::encryptString($value) : null;
    }

    /**
     * cert_key 복호화 조회
     */
    public function getCertKeyAttribute(?string $value): ?string
    {
        if (! $value) {
            return null;
        }

        try {
            return Crypt::decryptString($value);
        } catch (\Exception $e) {
            return null;
        }
    }

    // =========================================================================
    // 관계 정의
    // =========================================================================

    /**
     * 테넌트 관계
     */
    public function tenant(): BelongsTo
    {
        return $this->belongsTo(Tenant::class);
    }

    /**
     * 생성자 관계
     */
    public function creator(): BelongsTo
    {
        return $this->belongsTo(\App\Models\Members\User::class, 'created_by');
    }

    /**
     * 수정자 관계
     */
    public function updater(): BelongsTo
    {
        return $this->belongsTo(\App\Models\Members\User::class, 'updated_by');
    }

    // =========================================================================
    // 헬퍼 메서드
    // =========================================================================

    /**
     * 연동 가능 여부
     */
    public function canConnect(): bool
    {
        return $this->is_active
            && ! empty($this->corp_num)
            && ! empty($this->attributes['cert_key'])
            && ! empty($this->barobill_id);
    }

    /**
     * 검증 완료 여부
     */
    public function isVerified(): bool
    {
        return $this->verified_at !== null;
    }

    /**
     * 사업자번호 포맷 (하이픈 포함)
     */
    public function getFormattedCorpNumAttribute(): string
    {
        $num = $this->corp_num;
        if (strlen($num) === 10) {
            return substr($num, 0, 3).'-'.substr($num, 3, 2).'-'.substr($num, 5);
        }

        return $num;
    }
}
