<?php

namespace App\Domains\Tenant\Models;

use App\Domains\Attachable\Models\Attachment;
use App\Domains\Catalog\Enums\GroupLayout;
use App\Domains\Catalog\Enums\ProductLayout;
use App\Domains\Catalog\Models\CatalogItem;
use App\Domains\Catalog\Models\Category;
use App\Domains\Client\Models\Client;
use App\Domains\Event\Models\EventDate;
use App\Domains\Menu\Models\Menu;
use App\Domains\Menu\Models\TenantMenu;
use App\Domains\Tenant\Enums\CartEditingPolicy;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Support\Facades\Schema;

#[Fillable([
    'client_id',
    'codigo',
    'nombre',
    'dominio',
    'base_path',
    'site_title',
    'address',
    'phone',
    'primary_color',
    'secondary_color',
    'danger_color',
    'success_color',
    'header_bg_color',
    'footer_bg_color',
    'header_logo_id',
    'footer_logo_id',
    'favicon_id',
    'header_bg_image_id',
    'footer_bg_image_id',
    'website_type_code',
    'search_product_layout',
    'search_group_layout',
    'search_items_per_page',
    'display_categories',
    'display_seach_bar',
    'display_cart',
    'cart_editing_policy',
    'checkout_editing_policy',
    'display_cart_item_images',
    'scanner_category_validation_enabled',
    'event_title',
    'event_location',
    'event_date_text',
])]
class Tenant extends Model
{
    use HasFactory;

    protected $attributes = [
        'base_path' => '/',
        'search_product_layout' => ProductLayout::ColumnWithImage->value,
        'search_group_layout' => GroupLayout::Paginated->value,
        'search_items_per_page' => 12,
        'display_categories' => true,
        'display_seach_bar' => true,
        'display_cart' => true,
        'cart_editing_policy' => CartEditingPolicy::Full->value,
        'checkout_editing_policy' => CartEditingPolicy::Disabled->value,
        'display_cart_item_images' => true,
        'scanner_category_validation_enabled' => true,
    ];

    public function getRouteKeyName(): string
    {
        return 'codigo';
    }

    protected static function booted(): void
    {
        static::creating(function (Tenant $tenant): void {
            if ($tenant->client_id !== null || ! Schema::hasTable('clients')) {
                return;
            }

            $client = Client::query()->firstOrCreate(
                ['code' => $tenant->codigo],
                ['name' => $tenant->nombre],
            );

            $tenant->client()->associate($client);
        });
    }

    /** @return BelongsTo<Client, $this> */
    public function client(): BelongsTo
    {
        return $this->belongsTo(Client::class);
    }

    public function requiresScannerCategoryValidation(): bool
    {
        return $this->scanner_category_validation_enabled;
    }

    /**
     * Get the attributes that should be cast.
     *
     * @return array<string, string>
     */
    protected function casts(): array
    {
        return [
            'search_product_layout' => ProductLayout::class,
            'search_group_layout' => GroupLayout::class,
            'search_items_per_page' => 'integer',
            'display_categories' => 'boolean',
            'display_seach_bar' => 'boolean',
            'display_cart' => 'boolean',
            'cart_editing_policy' => CartEditingPolicy::class,
            'checkout_editing_policy' => CartEditingPolicy::class,
            'display_cart_item_images' => 'boolean',
            'scanner_category_validation_enabled' => 'boolean',
        ];
    }

    /**
     * @return BelongsTo<Attachment, $this>
     */
    public function headerLogo(): BelongsTo
    {
        return $this->belongsTo(Attachment::class, 'header_logo_id');
    }

    /**
     * @return BelongsTo<Attachment, $this>
     */
    public function footerLogo(): BelongsTo
    {
        return $this->belongsTo(Attachment::class, 'footer_logo_id');
    }

    /**
     * @return BelongsTo<Attachment, $this>
     */
    public function favicon(): BelongsTo
    {
        return $this->belongsTo(Attachment::class, 'favicon_id');
    }

    /**
     * @return BelongsTo<Attachment, $this>
     */
    public function headerBackgroundImage(): BelongsTo
    {
        return $this->belongsTo(Attachment::class, 'header_bg_image_id');
    }

    /**
     * @return BelongsTo<Attachment, $this>
     */
    public function footerBackgroundImage(): BelongsTo
    {
        return $this->belongsTo(Attachment::class, 'footer_bg_image_id');
    }

    /**
     * @return BelongsTo<WebsiteType, $this>
     */
    public function websiteType(): BelongsTo
    {
        return $this->belongsTo(WebsiteType::class, 'website_type_code', 'codigo');
    }

    public function catalogItems(): HasMany
    {
        return $this->hasMany(CatalogItem::class, 'tenant_code', 'codigo');
    }

    /** @return HasMany<EventDate, $this> */
    public function eventDates(): HasMany
    {
        return $this->hasMany(EventDate::class, 'tenant_code', 'codigo')
            ->orderBy('date')
            ->orderBy('time_start');
    }

    /**
     * @return HasMany<Category, $this>
     */
    public function categories(): HasMany
    {
        return $this->hasMany(Category::class, 'tenant_code', 'codigo');
    }

    /**
     * @return BelongsToMany<SocialMedia, $this>
     */
    public function socialMedia(): BelongsToMany
    {
        return $this->belongsToMany(
            SocialMedia::class,
            'tenant_social_media',
            'tenant_code',
            'social_media_code',
            'codigo',
            'code'
        )
            ->withPivot(['url', 'orden'])
            ->withTimestamps()
            ->orderByPivot('orden');
    }

    /**
     * @return HasMany<WebsiteExtra, $this>
     */
    public function websiteExtras(): HasMany
    {
        return $this->hasMany(WebsiteExtra::class, 'website_code', 'codigo');
    }

    public function menues(): BelongsToMany
    {
        return $this->belongsToMany(
            Menu::class,
            'tenants_menues',
            'tenant_code',
            'menu_code',
            'codigo',
            'code'
        )
            ->using(TenantMenu::class)
            ->withPivot('static_content')
            ->withTimestamps();
    }
}
