<?php

namespace App\Models;

use App\Models\Concerns\HasStatusLabels;
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\SoftDeletes;

class Service extends Model
{
    use HasFactory;
    use HasStatusLabels;
    use SoftDeletes;

    protected $fillable = [
        'title',
        'slug',
        'icon',
        'intro',
        'short_description',
        'description',
        'media_id',
        'image_alt',
        'image_position',
        'image_caption',
        'sort_order',
        'is_active',
        'status',
        'published_at',
        'created_by',
        'updated_by',
    ];

    protected $casts = [
        'is_active' => 'boolean',
        'published_at' => 'datetime',
    ];

    protected $appends = ['status_label', 'image', 'updated_at_demo', 'focus_areas'];

    public function media(): BelongsTo
    {
        return $this->belongsTo(Media::class);
    }

    public function highlights(): HasMany
    {
        return $this->hasMany(ServiceHighlight::class)->orderBy('sort_order');
    }

    public function scopeActive($query)
    {
        return $query->where('is_active', true);
    }

    public function scopeOrdered($query)
    {
        return $query->orderBy('sort_order')->orderBy('title');
    }

    protected function image(): Attribute
    {
        return Attribute::get(fn (): ?string => $this->media?->url);
    }

    protected function updatedAtDemo(): Attribute
    {
        return Attribute::get(fn (): string => optional($this->updated_at)->format('Y-m-d H:i') ?? '—');
    }

    protected function focusAreas(): Attribute
    {
        return Attribute::get(fn (): array => $this->relationLoaded('highlights')
            ? $this->highlights->pluck('text')->values()->all()
            : $this->highlights()->pluck('text')->values()->all());
    }
}
