<?php

namespace App\Services\Governance;

use App\Core\Database;
use PDO;

final class WorkflowHealthService
{
    public static function summary(): array
    {
        $db = Database::getInstance();

        $stmt = $db->query("
            SELECT
                id,
                submission_no,
                status,
                stage,
                workflow_stage,
                production_status,
                decision
            FROM submissions
            ORDER BY id DESC
        ");

        $healthy = 0;
        $warnings = 0;
        $errors = 0;

        $items = [];

        while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {

            $expected = self::expectedWorkflowStage(
                (string)$row['stage']
            );

            $state = 'healthy';
            $notes = [];

            if ($expected !== $row['workflow_stage']) {

                $state = 'warning';

                $notes[] =
                    "workflow_stage should be {$expected}";

            }

            if (
                $row['stage'] === 'production'
                &&
                $row['production_status'] === 'pending'
            ) {

                $state = 'warning';

                $notes[] =
                    'Production started without approval';

            }

            switch ($state) {

                case 'healthy':

                    $healthy++;

                    break;

                case 'warning':

                    $warnings++;

                    break;

                default:

                    $errors++;

            }

            $items[] = [

                'id' => (int)$row['id'],

                'submission_no' => $row['submission_no'],

                'status' => $row['status'],

                'stage' => $row['stage'],

                'workflow_stage' => $row['workflow_stage'],

                'state' => $state,

                'notes' => $notes

            ];

        }

        $total =
            max(
                1,
                $healthy + $warnings + $errors
            );

        $score =
            round(
                ($healthy / $total) * 100
            );

        return [

            'score' => $score,

            'healthy' => $healthy,

            'warnings' => $warnings,

            'errors' => $errors,

            'items' => $items

        ];
    }

    private static function expectedWorkflowStage(
        string $stage
    ): string {

        return match ($stage) {

            'submission' => 'submitted',

            'review' => 'under_review',

            'revision' => 'revision_required',

            'decision' => 'decision',

            'production' => 'production',

            'issue' => 'issue',

            'published' => 'published',

            default => 'submitted'

        };

    }
}
