<?php

namespace App\Models;

use App\Casts\EncryptedStringCast;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\HasMany;

class Vendor extends Model
{
    use HasFactory;

    protected $guarded = [];

    protected $hidden = [
        'secret_encrypted',
        'vtpass_api_key',
        'vtpass_public_key',
        'vtpass_secret_key',
    ];

    protected $casts = [
        'secret_encrypted' => EncryptedStringCast::class,
        'vtpass_api_key' => EncryptedStringCast::class,
        'vtpass_public_key' => EncryptedStringCast::class,
        'vtpass_secret_key' => EncryptedStringCast::class,
        'webhook_enabled' => 'boolean',
        'timeout_seconds' => 'integer',
        'last_checked_at' => 'datetime',
        'last_success_at' => 'datetime',
        'last_latency_ms' => 'integer',
    ];

    public function getSecretAttribute(): ?string
    {
        return $this->secret_encrypted;
    }

    public function setSecretAttribute(?string $value): void
    {
        $this->secret_encrypted = $value;
    }

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

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

    public function plans(): BelongsToMany
    {
        return $this->belongsToMany(Plan::class, 'plan_vendor_mappings')
            ->withPivot(['vendor_plan_code', 'priority', 'status', 'force_vendor', 'meta_json'])
            ->withTimestamps();
    }

    public function forcedPlans(): HasMany
    {
        return $this->hasMany(Plan::class, 'force_vendor_id');
    }

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

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