<?php

namespace App\Services;

use App\Models\Application;
use App\Models\ApplicationAssignment;
use App\Models\User;
use App\Models\WorkflowStage;

class ApplicationAssignmentService
{
    public function assignForStage(Application $application, WorkflowStage $stage, User $actor): ?User
    {
        $current = $application->assignedUser;
        if ($current && $stage->queue_role && $current->hasRole($stage->queue_role)) {
            return $current;
        }

        if (! $stage->queue_role) {
            return $current;
        }

        $candidates = User::where('tenant_id', $application->tenant_id)
            ->where('status', 'active')
            ->whereHas('roles', fn ($query) => $query->where('slug', $stage->queue_role))
            ->when($application->branch_id, function ($query) use ($application) {
                $query->where(function ($branchQuery) use ($application) {
                    $branchQuery->where('default_branch_id', $application->branch_id)
                        ->orWhereHas('allowedBranches', fn ($allowed) => $allowed->where('branches.id', $application->branch_id));
                });
            })
            ->get();

        $selected = $candidates->sortBy(function (User $candidate) use ($application) {
            return Application::withoutGlobalScopes()
                ->where('tenant_id', $application->tenant_id)
                ->where('assigned_user_id', $candidate->id)
                ->whereNotIn('status', ['completed', 'delivered', 'cancelled', 'rejected', 'archived'])
                ->count();
        })->first();

        $previousId = $application->assigned_user_id;
        $application->update(['assigned_user_id' => $selected?->id]);

        if ($selected && $previousId !== $selected->id) {
            ApplicationAssignment::create([
                'application_id' => $application->id,
                'assigned_from_id' => $previousId,
                'assigned_to_id' => $selected->id,
                'assignment_method' => 'least_workload_by_stage_role',
                'reason' => "Automatic handoff to {$stage->stage_name_en}",
                'assigned_by' => $actor->id,
            ]);
        }

        return $selected;
    }
}
