<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Storage;
use Spatie\MediaLibrary\HasMedia;
use Spatie\MediaLibrary\InteractsWithMedia;

class Service extends Model implements HasMedia
{
    use HasFactory, InteractsWithMedia;

    protected $guarded = [];

    protected function casts(): array
    {
        return [
            'benefits' => 'array',
            'applications' => 'array',
            'audience_sections' => 'array',
            'audiences' => 'array',
            'visual_steps' => 'array',
            'editorial_items' => 'array',
            'knowledge_sections' => 'array',
            'decision_content' => 'array',
            'simple_explanation' => 'array',
            'faqs' => 'array',
            'is_featured' => 'boolean',
            'is_published' => 'boolean',
        ];
    }

    public function scopePublished(Builder $query): Builder
    {
        return $query->where('is_published', true);
    }

    public function registerMediaCollections(): void
    {
        $this->addMediaCollection('hero')->singleFile();
        $this->addMediaCollection('gallery');
    }

    public function getRouteKeyName(): string
    {
        return 'slug';
    }

    public function imageUrl(): ?string
    {
        return $this->getFirstMediaUrl('hero') ?: ($this->existing_image ? asset($this->existing_image) : null);
    }

    public function editorialImageUrl(array $item): ?string
    {
        $path = $item['image'] ?? null;

        if (! $path) {
            return null;
        }

        return str_starts_with($path, 'images/') ? asset($path) : Storage::disk('public')->url($path);
    }
}
