<?php

namespace App\Domain\Communication\Models;

use App\Domain\Communication\Enums\NoteCategory;
use App\Domain\Communication\Enums\NoteVisibility;
use App\Domain\Identity\Models\User;
use App\Domain\Organization\Models\Company;
use App\Support\Concerns\HasUuid;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\MorphTo;
use Illuminate\Database\Eloquent\SoftDeletes;

class Note extends Model
{
    use HasFactory, HasUuid, SoftDeletes;

    protected $guarded = ['id', 'uuid'];

    protected function casts(): array
    {
        return [
            'category' => NoteCategory::class,
            'visibility' => NoteVisibility::class,
            'is_pinned' => 'boolean',
        ];
    }

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

    public function notable(): MorphTo
    {
        return $this->morphTo();
    }

    public function author(): BelongsTo
    {
        return $this->belongsTo(User::class, 'author_id');
    }

    /** Narrows to the visibility bands this reader is entitled to. */
    public function scopeReadableBy(Builder $query, User $user): Builder
    {
        $allowed = array_values(array_filter(
            NoteVisibility::cases(),
            fn (NoteVisibility $visibility) => $visibility->requiredPermission() === null
                || $user->can($visibility->requiredPermission()),
        ));

        return $query->whereIn('visibility', array_column($allowed, 'value'));
    }

    public function authorName(): string
    {
        return $this->author_name_snapshot ?? 'Unknown user';
    }
}
