<?php

declare(strict_types=1);

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

/**
 * Story Author - flexible author entity for the Stories system.
 *
 * @property int         $id
 * @property int|null    $user_id
 * @property string      $name
 * @property string|null $avatar
 * @property string|null $bio
 */
class StoryAuthor extends Model
{
    use HasFactory;

    protected $table = 'stories_authors';

    protected $fillable = [
        'user_id',
        'name',
        'avatar',
        'bio',
    ];

    // ── Relations ────────────────────────────────────────────────────────

    public function user()
    {
        return $this->belongsTo(User::class);
    }

    public function stories()
    {
        return $this->hasMany(Story::class, 'author_id');
    }

    // ── Accessors ────────────────────────────────────────────────────────

    public function getAvatarUrlAttribute(): string
    {
        if ($this->avatar) {
            return str_starts_with($this->avatar, 'http') ? $this->avatar : asset($this->avatar);
        }

        return asset('gfx/default-avatar.png');
    }

    public function getProfileUrlAttribute(): string
    {
        if ($this->user) {
            return url('/@' . $this->user->username);
        }

        return url('/stories');
    }
}
