<?php

declare(strict_types=1);

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;

class Category extends Model
{
    protected $fillable = [
        'name',
        'description',
        'intro',
        'keywords',
        'cover_path',
        'display_order',
        'articles_count',
    ];

    protected function casts(): array
    {
        return [
            'display_order' => 'integer',
            'articles_count' => 'integer',
        ];
    }

    public function articles(): HasMany
    {
        return $this->hasMany(Article::class);
    }

    public function publicUrl(): string
    {
        return url('/category-'.$this->id.'.shtml');
    }

    public function coverUrl(): ?string
    {
        $path = trim((string) $this->cover_path);
        if ($path === '') {
            return null;
        }

        if (str_starts_with($path, 'http://') || str_starts_with($path, 'https://')) {
            return $path;
        }

        return asset(ltrim($path, '/'));
    }
}
