<?php

namespace App\Http\Controllers\Agent;

use App\Http\Controllers\Controller;
use App\Models\Agent;
use App\Models\Candidate;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Str;

class AgentCandidateController extends Controller
{
    private function applyAgentVisibility(Builder $query, Agent $agent): Builder
    {
        if (Schema::hasColumn('candidates', 'agent_id')) {
            $query->where('agent_id', $agent->id);
        } elseif (Schema::hasColumn('candidates', 'agent_name') && !empty($agent->name)) {
            $query->where('agent_name', $agent->name);
        }

        if (Schema::hasTable('agent_company') && Schema::hasColumn('candidates', 'company_id')) {
            $allowedCompanyIds = $agent->allowedCompanies()->pluck('companies.id')->all();
            $query->whereIn('company_id', $allowedCompanyIds ?: [0]);
        }

        return $query;
    }

    private function canViewCandidate(Agent $agent, Candidate $candidate): bool
    {
        if (Schema::hasColumn('candidates', 'agent_id') && (int) $candidate->agent_id !== (int) $agent->id) {
            return false;
        }

        if (!Schema::hasColumn('candidates', 'agent_id') && Schema::hasColumn('candidates', 'agent_name') && !empty($agent->name)) {
            if (!empty($candidate->agent_name) && (string) $candidate->agent_name !== (string) $agent->name) {
                return false;
            }
        }

        if (Schema::hasTable('agent_company') && Schema::hasColumn('candidates', 'company_id')) {
            $allowedCompanyIds = $agent->allowedCompanies()->pluck('companies.id')->map(fn ($id) => (int) $id)->all();
            if (!in_array((int) $candidate->company_id, $allowedCompanyIds, true)) {
                return false;
            }
        }

        return true;
    }

    public function index()
    {
        $agent = Agent::where('user_id', Auth::id())->firstOrFail();

        $query = Candidate::query()->with(['company', 'recruitmentCase.currentStep'])->orderByDesc('id');
        $this->applyAgentVisibility($query, $agent);

        $candidates = $query->paginate(20)->withQueryString();

        return view('agent.candidates.index', compact('agent', 'candidates'));
    }

    public function show(Candidate $candidate)
    {
        $agent = Agent::where('user_id', Auth::id())->firstOrFail();

        if (!$this->canViewCandidate($agent, $candidate)) {
            return redirect()
                ->route('agent.candidates.index')
                ->with('error', 'You are not allowed to view that candidate.');
        }

        if (empty($candidate->public_track_token)) {
            $candidate->public_track_token = Str::random(60);
            $candidate->save();
        }

        $candidate->load([
            'agent',
            'company',
            'recruitmentCase.currentStep',
            'recruitmentCase.caseSteps.step',
            'recruitmentCase.payments',
            'recruitmentCase.expenses',
        ]);

        $case = $candidate->recruitmentCase;
        $history = $case
            ? $case->caseSteps()->with('step')->orderByDesc('id')->get()
            : collect();

        return view('agent.candidates.show', compact('agent', 'candidate', 'case', 'history'));
    }
}
