<?php

declare(strict_types=1);

namespace App\Services;

final class BranchReadinessPolicy
{
    /**
     * @return array<int, string>
     */
    public static function blockingQaBranches(): array
    {
        return self::normalizedList(
            (array)\config('branch_readiness.blocking_qa_branches', ['njch', 'mnh'])
        );
    }

    /**
     * @return array<int, string>
     */
    public static function databaseUpdateBranches(): array
    {
        return self::normalizedList(
            (array)\config('branch_readiness.database_update_branches', ['njch', 'jckh', 'mnh'])
        );
    }

    /**
     * @return array<int, string>
     */
    public static function deferredBranches(): array
    {
        $out = [];

        foreach ((array)\config('branch_readiness.branches', []) as $branch => $settings) {
            if (!is_array($settings)) {
                continue;
            }

            if ((string)($settings['state'] ?? '') === 'DEFERRED_NOT_READY') {
                $out[] = strtolower((string)$branch);
            }
        }

        return array_values(array_unique($out));
    }

    public static function state(string $branch): string
    {
        $branch = strtolower(trim($branch));

        return (string)\config(
            'branch_readiness.branches.' . $branch . '.state',
            'UNKNOWN'
        );
    }

    public static function isBlockingQa(string $branch): bool
    {
        return in_array(
            strtolower(trim($branch)),
            self::blockingQaBranches(),
            true
        );
    }

    public static function receivesDatabaseUpdates(string $branch): bool
    {
        return in_array(
            strtolower(trim($branch)),
            self::databaseUpdateBranches(),
            true
        );
    }

    /**
     * @return array<string, mixed>
     */
    public static function contract(): array
    {
        return [
            'policy' => (string)\config(
                'branch_readiness.policy',
                'READY_BRANCHES_ONLY_JCKH_DEFERRED'
            ),
            'blocking_qa_branches' => self::blockingQaBranches(),
            'deferred_branches' => self::deferredBranches(),
            'database_update_branches' => self::databaseUpdateBranches(),
            'branches' => (array)\config('branch_readiness.branches', []),
        ];
    }

    /**
     * @param array<int, mixed> $values
     * @return array<int, string>
     */
    private static function normalizedList(array $values): array
    {
        $out = [];

        foreach ($values as $value) {
            $branch = strtolower(trim((string)$value));

            if ($branch !== '') {
                $out[] = $branch;
            }
        }

        return array_values(array_unique($out));
    }
}
