<?php

namespace App\Models;

use App\Enums\CatalogReviewStatus;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;

class Venue extends Model
{
    use SoftDeletes;

    protected $fillable = [
        'name',
        'slug',
        'catalog_review_status',
        'catalog_submitted_by',
        'address_line_1',
        'address_line_2',
        'city',
        'region',
        'postal_code',
        'country',
        'timezone',
        'latitude',
        'longitude',
        'metadata',
    ];

    protected function casts(): array
    {
        return [
            'metadata' => 'array',
            'latitude' => 'decimal:7',
            'longitude' => 'decimal:7',
            'catalog_review_status' => CatalogReviewStatus::class,
        ];
    }

    public function submittedBy(): BelongsTo
    {
        return $this->belongsTo(User::class, 'catalog_submitted_by');
    }

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

    /**
     * @param  mixed  $value
     */
    public function resolveRouteBinding($value, $field = null): Model
    {
        $field ??= $this->getRouteKeyName();

        $query = static::query();
        if (request()->is('dashboard/*')) {
            $query = static::withTrashed();
        }

        return $query->where($field, $value)->firstOrFail();
    }

    public function isSelectableBy(User $user): bool
    {
        if ($user->hasRole(Role::SLUG_SUPER_ADMIN) || $user->hasRole(Role::SLUG_ADMINISTRADOR)) {
            return true;
        }
        if ($this->catalog_review_status === CatalogReviewStatus::Approved) {
            return true;
        }

        return $this->catalog_review_status === CatalogReviewStatus::PendingReview
            && $this->catalog_submitted_by !== null
            && (int) $this->catalog_submitted_by === (int) $user->id;
    }

    /**
     * Sedas visibles en el selector del formulario de evento para este usuario.
     *
     * @return Builder<Venue>
     */
    public static function querySelectableForDashboardUser(User $user): Builder
    {
        $q = static::query()->orderBy('name');
        if ($user->hasRole(Role::SLUG_SUPER_ADMIN) || $user->hasRole(Role::SLUG_ADMINISTRADOR)) {
            return $q;
        }

        return $q->where(function (Builder $sub) use ($user): void {
            $sub->where('catalog_review_status', CatalogReviewStatus::Approved->value)
                ->orWhere(function (Builder $inner) use ($user): void {
                    $inner->where('catalog_review_status', CatalogReviewStatus::PendingReview->value)
                        ->where('catalog_submitted_by', $user->id);
                });
        });
    }
}
