<?php

namespace App\Services;

use App\Core\Database;

class ReviewConflictService
{
    public static function check(
        int $submissionId,
        int $reviewerId
    ): ?string
    {
        $db =
            Database::getInstance();

        /*
        1 — Self-review check
        */

        $stmt =
            $db->prepare("
                SELECT id
                FROM submission_authors
                WHERE submission_id = ?
                AND (
                    email =
                        (
                            SELECT email
                            FROM users
                            WHERE id = ?
                        )
                )
                LIMIT 1
            ");

        $stmt->execute([
            $submissionId,
            $reviewerId
        ]);

        if ($stmt->fetchColumn()) {

            return
                "Reviewer is an author of this submission.";

        }

        /*
        2 — Duplicate assignment
        */

        $stmt =
            $db->prepare("
                SELECT id
                FROM review_assignments
                WHERE submission_id = ?
                AND reviewer_id = ?
                LIMIT 1
            ");

        $stmt->execute([
            $submissionId,
            $reviewerId
        ]);

        if ($stmt->fetchColumn()) {

            return
                "Reviewer already assigned.";

        }

        /*
        3 — Same round completed
        */

        $stmt =
            $db->prepare("
                SELECT id
                FROM reviews
                WHERE submission_id = ?
                AND reviewer_id = ?
                LIMIT 1
            ");

        $stmt->execute([
            $submissionId,
            $reviewerId
        ]);

        if ($stmt->fetchColumn()) {

            return
                "Reviewer already reviewed this submission.";

        }

        /*
        No conflict
        */

        return null;
    }
}
