<?php

declare(strict_types=1);

namespace App\Models;

use App\Services\BranchAccessService;
use Database\Factories\MemberNoteFactory;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class MemberNote extends Model
{
    /** @use HasFactory<MemberNoteFactory> */
    use HasFactory;

    protected $fillable = [
        'member_id',
        'user_id',
        'body',
        'is_private',
    ];

    protected function casts(): array
    {
        return [
            'is_private' => 'boolean',
        ];
    }

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

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

    public function scopeVisibleTo(Builder $query, User $user): Builder
    {
        $branchIds = app(BranchAccessService::class)->accessibleBranchIds($user);

        if ($branchIds === null) {
            return $query;
        }

        return $query->whereHas('member', fn (Builder $q) => $q->whereIn('branch_id', $branchIds));
    }

    public function resolveRouteBinding($value, $field = null)
    {
        $query = static::query();
        $user = auth()->user();

        if ($user) {
            $query->visibleTo($user);
        }

        return $query->where($field ?? $this->getRouteKeyName(), $value)->first();
    }
}
