<?php

namespace App\Services;

use App\Core\Database;

class ReviewerAutoAssignService
{
    public static function suggestReviewers(
        int $submissionId,
        int $conferenceId,
        int $limit = 3
    ): array
    {
        $db =
            Database::getInstance();

        /*
        Get all reviewers in this conference
        */

        $stmt =
            $db->prepare("
                SELECT
                    u.id,
                    u.first_name,
                    u.last_name
                FROM users u
                JOIN conference_user_roles cur
                    ON cur.user_id = u.id
                WHERE cur.conference_id = ?
                AND cur.role_code = 'reviewer'
            ");

        $stmt->execute([
            $conferenceId
        ]);

        $reviewers =
            $stmt->fetchAll(\PDO::FETCH_ASSOC);

        $candidates = [];

        foreach ($reviewers as $r) {

            $reviewerId =
                (int)$r['id'];

            /*
            Skip conflicts
            */

            $conflict =
                \App\Services\ReviewConflictService::check(

                    $submissionId,

                    $reviewerId

                );

            if ($conflict) {

                continue;

            }

            /*
            Get workload
            */

            $load =
                \App\Services\ReviewerLoadService::getReviewerLoad(

                    $reviewerId,

                    $conferenceId

                );

            $candidates[] = [

                'id' =>
                    $reviewerId,

                'name' =>
                    trim(
                        $r['first_name']
                        . ' '
                        . $r['last_name']
                    ),

                'load' =>
                    $load

            ];

        }

        /*
        Sort by lowest workload
        */

        usort(

            $candidates,

            function ($a, $b) {

                return
                    $a['load']
                    <=>
                    $b['load'];

            }

        );

        return
            array_slice(

                $candidates,

                0,

                $limit

            );
    }
}
