<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasOne;
use Illuminate\Support\Facades\DB;

class ProviderConnection extends Model
{
    use HasFactory;

    protected $guarded = [];

    protected $casts = [
        'is_default' => 'boolean',
        'scopes_granted' => 'array',
        'metadata' => 'array',
        'last_health_check_at' => 'datetime',
    ];

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

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

    public function credential(): HasOne
    {
        return $this->hasOne(ProviderCredential::class, 'provider_connection_id');
    }

    public function makeDefault(): void
    {
        DB::transaction(function (): void {
            static::query()
                ->where('tenant_id', $this->tenant_id)
                ->where('provider', $this->provider)
                ->where('is_default', true)
                ->whereKeyNot($this->getKey())
                ->update(['is_default' => false]);

            static::query()
                ->whereKey($this->getKey())
                ->update(['is_default' => true]);
        });

        $this->refresh();
    }
}
