<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class ApiProvider extends Model
{
    use HasFactory;

    protected $fillable = [
        'name',
        'api_url',
        'username',
        'password',
        'token',
        'plugin',
        'enabled',
        'last_checked_at',
        'last_status',
        'last_response_time_ms',
        'last_error',
    ];

    protected $casts = [
        'enabled' => 'boolean',
        'last_checked_at' => 'datetime',
        'last_response_time_ms' => 'integer',
    ];

    public function disableWithDependencies()
    {
        $this->enabled = false;
        $this->save();

        // Deaktiviere alle zugehörigen Modelle
        foreach ($this->aiModels as $model) {
            $model->enabled = false;
            $model->save();

            // Deaktiviere alle zugehörigen Styles
            foreach ($model->styles as $style) {
                $style->enabled = false;
                $style->save();
            }
        }

        return true;
    }

    public function styles()
    {
        return $this->hasMany(Style::class);
    }

    public function aiModels()
    {
        return $this->hasMany(AiModel::class, 'api_provider_id');
    }

    public function getDashboardUrl(): ?string
    {
        return match ($this->plugin) {
            'runwareai' => 'https://my.runware.ai/home',
            'leonardoai' => 'https://app.leonardo.ai/settings/profile',
            'comfyui' => $this->comfyDashboardUrl(),
            default => null,
        };
    }

    private function comfyDashboardUrl(): ?string
    {
        if (! $this->api_url) {
            return null;
        }

        $parts = parse_url($this->api_url);
        $scheme = $parts['scheme'] ?? 'http';
        $host = $parts['host'] ?? null;
        $port = isset($parts['port']) ? ':'.$parts['port'] : '';

        if (! $host) {
            return null;
        }

        return $scheme.'://'.$host.$port.'/';
    }
}
