<?php

namespace App\Models\Task;

use App\Models\Customer\Customer;
use App\Models\DayTour\DayTourDate;
use App\Models\InternationalTour\InternationalTourDate;
use App\Models\Product\DayTripTourDate;
use App\Models\Resource;
use App\Models\Sale\Sale;
use App\Models\Supplier\Supplier;
use App\Models\Tour\TourDate;
use Illuminate\Database\Eloquent\Model;

class TaskRelation extends Model
{
    protected $table = 'task_relations';

    protected $fillable = [
        'task_id',
        'related_type',
        'related_id',
        'is_primary',
    ];

    protected $casts = [
        'is_primary' => 'boolean',
    ];

    /**
     * Göreve bağlanabilir varlık beyaz listesi.
     * alias => [sınıf, TR etiket, FA ikon, operations tip anahtarı (kalkışlar için)]
     */
    public const LINKABLE = [
        'customer' => ['class' => Customer::class, 'label' => 'Müşteri', 'icon' => 'fa-user', 'op_type' => null],
        'sale' => ['class' => Sale::class, 'label' => 'Satış', 'icon' => 'fa-shopping-cart', 'op_type' => null],
        'supplier' => ['class' => Supplier::class, 'label' => 'Tedarikçi', 'icon' => 'fa-handshake', 'op_type' => null],
        'resource' => ['class' => Resource::class, 'label' => 'Kaynak', 'icon' => 'fa-id-badge', 'op_type' => null],
        'tour_date' => ['class' => TourDate::class, 'label' => 'Tur Kalkışı', 'icon' => 'fa-landmark', 'op_type' => 'cultural'],
        'international_tour_date' => ['class' => InternationalTourDate::class, 'label' => 'Yurt Dışı Kalkış', 'icon' => 'fa-plane', 'op_type' => 'international'],
        'day_tour_date' => ['class' => DayTourDate::class, 'label' => 'Günübirlik Kalkış', 'icon' => 'fa-sun', 'op_type' => 'day_tour'],
        'day_trip_tour_date' => ['class' => DayTripTourDate::class, 'label' => 'Günübirlik Kalkış', 'icon' => 'fa-sun', 'op_type' => 'day_trip'],
        'task' => ['class' => Task::class, 'label' => 'Görev', 'icon' => 'fa-list-check', 'op_type' => null],
    ];

    public function task()
    {
        return $this->belongsTo(Task::class);
    }

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

    /** Sınıf adından alias çözer (Task quick-view chip'leri için). */
    public static function aliasFor(string $class): ?string
    {
        foreach (self::LINKABLE as $alias => $meta) {
            if ($meta['class'] === $class) {
                return $alias;
            }
        }

        return null;
    }

    public function meta(): array
    {
        $alias = self::aliasFor($this->related_type);

        return $alias
            ? self::LINKABLE[$alias]
            : ['class' => $this->related_type, 'label' => 'Kayıt', 'icon' => 'fa-link', 'op_type' => null];
    }

    /** Chip metni: "Satış · SAL-123" gibi. */
    public function label(): string
    {
        $meta = $this->meta();
        $entity = $this->related;

        if (! $entity) {
            return $meta['label'] . ' · #' . $this->related_id;
        }

        $name = match (self::aliasFor($this->related_type)) {
            'customer' => $entity->full_name ?? $entity->company_name,
            'sale' => $entity->sale_code ?: $entity->title,
            'supplier' => $entity->company_name,
            'resource' => $entity->name,
            'task' => $entity->title,
            'tour_date', 'international_tour_date', 'day_tour_date', 'day_trip_tour_date' => trim(
                ($entity->tour?->name ?? 'Tur') . ' — ' . ($entity->start_date?->format('d.m.Y') ?? '')
            , ' —'),
            default => null,
        };

        return $meta['label'] . ' · ' . ($name ?: '#' . $this->related_id);
    }

    /** İlgili varlığın quick-view drawer URL'i (yoksa null). */
    public function quickViewUrl(): ?string
    {
        $alias = self::aliasFor($this->related_type);

        return match ($alias) {
            'customer' => route('agency.customers.quick-view', $this->related_id),
            'sale' => route('agency.sales.quick-view', $this->related_id),
            'supplier' => route('agency.suppliers.quick-view', $this->related_id),
            'resource' => route('agency.resources.quick-view', $this->related_id),
            'task' => route('agency.tasks.quick-view', $this->related_id),
            'tour_date', 'international_tour_date', 'day_tour_date', 'day_trip_tour_date' => route(
                'agency.operations.quick-view',
                [self::LINKABLE[$alias]['op_type'], $this->related_id]
            ),
            default => null,
        };
    }
}
