<?php

namespace App\Models\Scopes;

use App\Models\User;
use App\Services\BranchAccessService;
use App\Services\BranchContext;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Scope;
use Illuminate\Support\Facades\Auth;

class FinancialTransferScope implements Scope
{
    public function apply(Builder $builder, Model $model): void
    {
        $user = Auth::user();

        if ($user instanceof User) {
            $branchAccess = app(BranchAccessService::class);
            if ($branchAccess->isSystemWide($user)) {
                return;
            }

            $branchIds = $branchAccess->accessibleBranchIds($user);
        } else {
            $context = app(BranchContext::class);
            if ($context->isSystemWide()) {
                return;
            }

            $branchIds = $context->branchIds();
            if ($branchIds === null) {
                $builder->whereRaw('1 = 0');
                return;
            }
        }

        if ($branchIds === []) {
            $builder->whereRaw('1 = 0');
            return;
        }

        $builder
            ->whereIn($model->qualifyColumn('source_account_id'), function ($query) use ($branchIds): void {
                $query->select('id')
                    ->from('financial_accounts')
                    ->whereIn('branch_id', $branchIds);
            })
            ->whereIn($model->qualifyColumn('destination_account_id'), function ($query) use ($branchIds): void {
                $query->select('id')
                    ->from('financial_accounts')
                    ->whereIn('branch_id', $branchIds);
            });
    }
}
