<?php

namespace App\Models;

use App\Models\Locations\Location;
use Cog\Contracts\Love\Reactable\Models\Reactable as ReactableInterface;
use Cog\Laravel\Love\Reactable\Models\Traits\Reactable;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
use Laravel\Scout\Searchable;

class Call extends Model implements ReactableInterface
{
    use HasFactory;
    use SoftDeletes;
    use Searchable;
    use Reactable;

    protected $fillable = [
        'callable_id',
        'callable_type',
        'tag_id',
        'location_id',
        'from',
        'till',
        'is_public',
        'is_suppressed',
        'is_paused',
    ];

    protected $casts = [
        'from'          => 'datetime',
        'till'          => 'datetime',
        'is_public'     => 'boolean',
        'is_suppressed' => 'boolean',
        'is_paused'     => 'boolean',
    ];

    public function callable()
    {
        return $this->morphTo();
    }

    public function translations()
    {
        return $this->hasMany(CallTranslation::class);
    }

    public function tag()
    {
        return $this->belongsTo(Tag::class, 'tag_id', 'tag_id');
    }

    public function location()
    {
        return $this->belongsTo(Location::class);
    }

    public function searchableAs(): string
    {
        return 'calls_index';
    }

    public function shouldBeSearchable(): bool
    {
        // Only index active (non-deleted, non-expired, non-blocked) calls
        if ($this->trashed()) {
            return false;
        }
        if ($this->till !== null && $this->till->isPast()) {
            return false;
        }
        if ($this->is_suppressed) {
            return false;
        }
        if ($this->is_paused) {
            return false;
        }
        return true;
    }

    public function toSearchableArray(): array
    {
        $tag = $this->tag;
        $tagNames = [];
        if ($tag) {
            foreach (['en', 'nl', 'fr', 'de', 'es'] as $locale) {
                $trans = $tag->translations()->firstWhere('locale', $locale);
                $tagNames['name_' . $locale] = $trans ? $trans->name : $tag->name;
            }
        }

        $location = $this->location;
        $locationData = [
            'city'     => $location?->city?->translations->map(fn($t) => $t->name)->toArray() ?? [],
            'division' => $location?->division?->translations->map(fn($t) => $t->name)->toArray() ?? [],
            'country'  => $location?->country?->translations->map(fn($t) => $t->name)->toArray() ?? [],
        ];

        return [
            'id'           => $this->id,
            '__class_name' => self::class,
            'callable'     => [
                'id'   => $this->callable?->id,
                'name' => $this->callable?->name,
            ],
            'tag' => array_merge(
                ['tag_id' => $tag?->tag_id, 'color' => $tag?->contexts->first()?->category?->relatedColor ?? 'gray'],
                $tagNames
            ),
            'location' => $locationData,
            'from'      => $this->from?->utc()->format('Y-m-d H:i:s'),
            'till'      => $this->till?->utc()->format('Y-m-d H:i:s'),
            'is_public' => (bool) $this->is_public,
            'call_translations' => $this->translations->mapWithKeys(fn($t) => [
                'content_' . $t->locale => $t->content,
            ])->toArray(),
        ];
    }
}
