<?php

namespace App\Domain\Shared\Traits;

use App\Domain\Shared\Models\Academy;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

trait BelongsToAcademy
{
    public static function bootBelongsToAcademy(): void
    {
        static::creating(function ($model) {
            if (! $model->academy_id && app()->has('current_academy')) {
                $model->academy_id = app('current_academy')->id;
            }
        });

        static::addGlobalScope('academy', function (Builder $builder) {
            if (app()->has('current_academy')) {
                $builder->where(
                    $builder->getModel()->getTable() . '.academy_id',
                    app('current_academy')->id
                );
            }
        });
    }

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