<?php

namespace Modules\Catalog\Models;

use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Modules\Catalog\Database\Factories\EvCompanyFactory;
use Spatie\Activitylog\Models\Concerns\LogsActivity;
use Spatie\Activitylog\Support\LogOptions;

class EvCompany extends Model
{
    /** @use HasFactory<EvCompanyFactory> */
    use HasFactory, LogsActivity;

    /**
     * Full CRUD audit trail — catalog admin writes are staff-only and
     * infrequent, so logging every attribute change is affordable
     * (domain.md §6; T6.2).
     */
    public function getActivitylogOptions(): LogOptions
    {
        return LogOptions::defaults()
            ->logFillable()
            ->logOnlyDirty()
            ->dontLogEmptyChanges()
            ->useLogName('catalog');
    }

    /**
     * @var list<string>
     */
    protected $fillable = [
        'name',
        'mm_name',
        'slug',
        'description',
        'mm_description',
        'contact',
        'address',
        'logo',
        'is_active',
    ];

    protected static function booted(): void
    {
        static::creating(function (self $evCompany): void {
            if (filled($evCompany->slug)) {
                return;
            }

            $slug = Str::slug($evCompany->name);
            $uniqueSlug = $slug;
            $suffix = 1;

            while (static::where('slug', $uniqueSlug)->exists()) {
                $uniqueSlug = "{$slug}-{$suffix}";
                $suffix++;
            }

            $evCompany->slug = $uniqueSlug;
        });
    }

    /**
     * @return array<string, string>
     */
    protected function casts(): array
    {
        return [
            'is_active' => 'boolean',
        ];
    }

    /**
     * `logo` is stored as the disk-relative path Filament's FileUpload
     * writes (e.g. "logos/xxx.png"), not a URL — API consumers need a full
     * absolute URL to render it directly. Logos are always written to the
     * "public" disk (storage/app/public, symlinked to public/storage) so
     * the frontend can actually reach the image, regardless of what the
     * app's default filesystem disk is configured to.
     */
    public function logoUrl(): Attribute
    {
        return Attribute::make(
            get: function (): ?string {
                if (blank($this->logo)) {
                    return null;
                }

                $url = Storage::disk('public')->url($this->logo);

                return str($url)->startsWith(['http://', 'https://']) ? $url : url($url);
            },
        );
    }
}
