<?php

namespace App\Models;

use App\Traits\LogsActivity;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\MorphMany;
use Illuminate\Database\Eloquent\SoftDeletes;
use Laravel\Scout\Searchable;

class Feature extends Model
{
    use LogsActivity, SoftDeletes, Searchable;

    const STATUSES = ['planned', 'started', 'in_progress', 'completed', 'verified'];

    protected $fillable = [
        'layer_id', 'name', 'geometry', 'properties', 'template_id', 'feature_type_id',
        'progress', 'status', 'is_active', 'responsible', 'responsible_user_id',
        'uuid', 'client_updated_at',
        'planned_start', 'planned_end', 'actual_start', 'actual_end',
        'baseline_start', 'baseline_end',
    ];

    protected $casts = [
        'geometry' => 'array',
        'properties' => 'array',
        'is_active' => 'boolean',
        'planned_start' => 'date',
        'planned_end' => 'date',
        'actual_start' => 'date',
        'actual_end' => 'date',
        'baseline_start' => 'date',
        'baseline_end' => 'date',
    ];

    public function featureType()
    {
        return $this->belongsTo(FeatureType::class);
    }

    public function layer()
    {
        return $this->belongsTo(Layer::class);
    }

    public function template()
    {
        return $this->belongsTo(InspectionTemplate::class);
    }

    public function inspections()
    {
        return $this->hasMany(Inspection::class, 'feature_id');
    }

    public function issues()
    {
        return $this->hasMany(Issue::class);
    }

    public function responsibleUser()
    {
        return $this->belongsTo(User::class, 'responsible_user_id');
    }

    public function media()
    {
        return $this->morphMany(Media::class, 'mediable');
    }

    public function images()
    {
        return $this->morphMany(Media::class, 'mediable')->where('category', 'image');
    }

    public function progressSnapshots(): MorphMany
    {
        return $this->morphMany(ProgressSnapshot::class, 'trackable');
    }

    public function getStatusColorAttribute(): string
    {
        return match ($this->status) {
            'planned' => '#6b7280',
            'started' => '#3b82f6',
            'in_progress' => '#f59e0b',
            'completed' => '#10b981',
            'verified' => '#8b5cf6',
            default => '#6b7280',
        };
    }

    /**
     * Deviation in days: positive = delayed, negative = early
     */
    public function getDeviationDaysAttribute(): ?int
    {
        if (! $this->planned_end) {
            return null;
        }
        $end = $this->actual_end ?? now()->toDateString();

        return $this->planned_end->diffInDays($end, false);
    }

    public function getStartDeviationDaysAttribute(): ?int
    {
        if (! $this->planned_start) {
            return null;
        }
        $start = $this->actual_start ?? now()->toDateString();

        return $this->planned_start->diffInDays($start, false);
    }

    public function getPlannedProgressAtAttribute(?Carbon $date = null): float
    {
        $date = $date ?? now();

        if (! $this->planned_start || ! $this->planned_end) {
            return 0;
        }

        if ($date <= $this->planned_start) {
            return 0;
        }
        if ($date >= $this->planned_end) {
            return 100;
        }

        $totalDays = $this->planned_start->diffInDays($this->planned_end);
        $elapsedDays = $this->planned_start->diffInDays($date);

        return round(($elapsedDays / $totalDays) * 100, 2);
    }

    public function getSpiAttribute(): ?float
    {
        $pv = $this->planned_progress_at;
        $ev = $this->progress;

        if ($pv <= 0) {
            return null;
        }

        return round($ev / $pv, 2);
    }

    public function getIsOnTrackAttribute(): ?bool
    {
        $spi = $this->spi;
        if ($spi === null) {
            return null;
        }

        return $spi >= 0.95;
    }

    public function toSearchableArray(): array
    {
        return [
            'id' => $this->id,
            'name' => $this->name,
            'description' => $this->description,
            'project_id' => $this->layer->phase->project_id ?? null,
            'phase_id' => $this->layer->phase_id ?? null,
            'layer_id' => $this->layer_id ?? null,
            'status' => $this->status,
            'progress' => $this->progress,
        ];
    }

    public function getScoutKey(): string
    {
        return (string) $this->id;
    }
}
