<?php

namespace App\Models\Scopes;

use App\Models\Company;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Scope;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Schema;

class CompanyScope implements Scope
{
    /**
     * Apply the scope to a given Eloquent query builder.
     */
    public function apply(Builder $builder, Model $model): void
    {
        // Only apply if user is authenticated
        // (Avoid calling auth()->user() when not logged in)
        if (! Auth::check()) {
            return;
        }

        $user = Auth::user();

        // Check if user has company_id
        if (! Schema::hasColumn('users', 'company_id') || ! $user->company_id) {
            return;
        }

        $table = $model->getTable();

        // Get permission table names from config
        $permissionTables = config('permission.table_names', []);

        // Skip system tables that shouldn't have company_id scope
        $excludedTables = array_merge([
            'settings', // Prevent circular dependency
            'users', // User authentication
            'companies', // Company table itself
            'password_reset_tokens', // Laravel auth
            'personal_access_tokens', // Laravel Sanctum
            'sessions', // Laravel sessions
            'cache', // Laravel cache
            'cache_locks', // Laravel cache
            'jobs', // Laravel queue
            'job_batches', // Laravel queue
            'failed_jobs', // Laravel queue
        ], array_values($permissionTables)); // Add all Spatie Permission tables

        if (in_array($table, $excludedTables)) {
            return;
        }

        // Prevent circular dependency: Don't apply scope to Company model queries
        if ($model instanceof Company) {
            return;
        }

        // Get company data directly without cache
        $company = Company::withoutGlobalScopes()->find($user->company_id);
        if (! $company) {
            return;
        }

        $companyData = [
            'company_id' => $company->id,
            'business_id' => $company->business_type_id ?? null,
        ];

        // Apply company_id filter if column exists
        if (Schema::hasColumn($table, 'company_id')) {
            $builder->where($table.'.company_id', $companyData['company_id']);
        }

        // // Apply business_id filter if column exists and company has business_id
        // if ($companyData['business_id'] && Schema::hasColumn($table, 'business_id')) {
        //     $builder->where($table.'.business_id', $companyData['business_id']);
        // }
    }
}
