<?php

namespace App\Models\Concerns;

use App\Models\Expense;
use App\Models\JournalEntry;
use App\Models\Payment;
use App\Models\Purchase;
use App\Models\PurchaseReturn;
use App\Models\Receipt;
use App\Models\Sale;
use App\Models\SalesReturn;
use App\Models\VanSession;
use App\Services\BranchAccessService;
use Illuminate\Database\Eloquent\Builder;

trait BranchScoped
{
    public static function bootBranchScoped(): void
    {
        static::addGlobalScope('permitted_branch', function (Builder $builder) {
            $module = match (static::class) {
                Sale::class, SalesReturn::class => 'sales',
                Purchase::class, PurchaseReturn::class => 'purchases',
                Receipt::class => 'receipts',
                Payment::class => 'payments',
                Expense::class => 'expenses',
                VanSession::class => 'van-sales',
                JournalEntry::class => 'accounts',
                default => 'dashboard',
            };
            $ids = app(BranchAccessService::class)->allowedBranchIds($module);
            if ($ids !== null) {
                $ids ? $builder->whereIn($builder->qualifyColumn('branch_id'), $ids) : $builder->whereRaw('1 = 0');
            }
        });
    }
}
