# SPDX-FileCopyrightText: UL Research Institutes
# SPDX-License-Identifier: Apache-2.0

import pytest

from cici.providers.gitlab import models as gitlab
from cici.providers.gitlab.serializers import expand_job_extends


@pytest.mark.parametrize(
    "parents, child, expected",
    [
        # multiple parents merge variables without loss
        (
            {
                "parent_a": {"A": "1", "B": "1"},
                "parent_b": {"C": "1"},
            },
            {
                "extends": ["parent_a", "parent_b"],
                "variables": {},
            },
            {
                "A": "1",
                "B": "1",
                "C": "1",
            },
        ),
        # child overrides parent but keeps other keys
        (
            {
                "parent_a": {"A": "1", "B": "1"},
            },
            {
                "extends": ["parent_a"],
                "variables": {"B": "2"},
            },
            {
                "A": "1",
                "B": "2",
            },
        ),
        # later parent overrides earlier parent on conflicts
        (
            {
                "parent_a": {"A": "1"},
                "parent_b": {"A": "2"},
            },
            {
                "extends": ["parent_a", "parent_b"],
                "variables": {},
            },
            {
                "A": "2",
            },
        ),
        # later parent overrides earlier parent on conflicts but keeps previous values
        (
            {
                "parent_a": {"A": "1", "B": "1"},
                "parent_b": {"A": "2", "C": "3"},
            },
            {
                "extends": ["parent_a", "parent_b"],
                "variables": {},
            },
            {
                "A": "2",
                "B": "1",
                "C": "3",
            },
        ),
    ],
    ids=[
        "parents merge without loss",
        "child overrides parent",
        "later parent overrides earlier parent",
        "merge and override",
    ],
)
def test_expand_job_extends_variable_merging(parents, child, expected):
    jobs = {}
    # create parent jobs
    for name, variables in parents.items():
        jobs[name] = gitlab.Job(variables=variables)
    # create child job
    jobs["child"] = gitlab.Job(
        extends=child["extends"],
        variables=child["variables"],
    )
    expanded = expand_job_extends(
        jobs,
        jobs["child"],
        root_name="child",
    )
    assert expanded.extends in (None, [], "")
    assert expanded.variables == expected
