<?php

namespace App\Models\Concerns;

use App\Models\Company;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

/**
 * Scopes a model to the company resolved for the current request (see
 * ResolveTenant) and stamps new rows with it automatically.
 *
 * Deliberately opt-in per model rather than applied blanket across the
 * schema: turning this on for a model whose existing controllers don't yet
 * pass company_id on every write would silently start hiding data those
 * controllers still expect to see. Wire it in one model at a time, checking
 * that model's read/write paths as you go — see Setting for the first one.
 *
 * When no company is resolved (CLI, artisan commands, the SaaS control
 * panel's own root-admin context) the scope is a no-op, so seeders and
 * platform-level tooling keep seeing every row.
 */
trait BelongsToCompany
{
    public static function bootBelongsToCompany(): void
    {
        static::addGlobalScope('company', function (Builder $builder) {
            if ($companyId = currentCompanyId()) {
                $builder->where($builder->getModel()->getTable() . '.company_id', $companyId);
            }
        });

        static::creating(function ($model) {
            if (!$model->company_id && $companyId = currentCompanyId()) {
                $model->company_id = $companyId;
            }
        });
    }

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