<?php

namespace App\Domains\Tenant\Models;

use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

#[Fillable([
    'website_code',
    'website_type_extra_id',
    'config',
    'is_enabled',
])]
class WebsiteExtra extends Model
{
    use HasFactory;

    protected $table = 'websites_extras';

    protected $attributes = [
        'is_enabled' => true,
    ];

    private mixed $resolvedConfig = null;

    private bool $hasResolvedConfig = false;

    /**
     * @return array<string, string>
     */
    protected function casts(): array
    {
        return [
            'website_type_extra_id' => 'integer',
            'config' => 'array',
            'is_enabled' => 'boolean',
        ];
    }

    /**
     * @return BelongsTo<Tenant, $this>
     */
    public function website(): BelongsTo
    {
        return $this->belongsTo(Tenant::class, 'website_code', 'codigo');
    }

    /**
     * @return BelongsTo<WebsiteTypeExtra, $this>
     */
    public function websiteTypeExtra(): BelongsTo
    {
        return $this->belongsTo(WebsiteTypeExtra::class, 'website_type_extra_id');
    }

    public function setResolvedConfig(mixed $config): self
    {
        $this->resolvedConfig = $config;
        $this->hasResolvedConfig = true;

        return $this;
    }

    public function resolvedConfig(): mixed
    {
        return $this->hasResolvedConfig ? $this->resolvedConfig : $this->config;
    }
}
