import pytest
from fastapi import HTTPException

from src.api.v1.forms import _parse_sections_csv, _validate_sheet_query_params
from src.api.v1.projects import _parse_sections
from src.db.models.form_type import FormTypeEnum
from src.domain.schemas import DirectionSchemaEnum


def test_parse_sections_csv_returns_none_for_empty_values():
    assert _parse_sections_csv(None) is None
    assert _parse_sections_csv("") is None
    assert _parse_sections_csv(" , , ") is None


def test_parse_sections_csv_splits_and_trims():
    assert _parse_sections_csv("plan, q1, q2 ") == ["plan", "q1", "q2"]


def test_validate_sheet_query_requires_direction_for_form1_ahr_cap():
    with pytest.raises(HTTPException) as exc:
        _validate_sheet_query_params(FormTypeEnum.FORM_1, "AHR", None, None)
    assert exc.value.status_code == 400


def test_validate_sheet_query_rejects_direction_for_non_form1_or_non_ahr_cap():
    with pytest.raises(HTTPException) as exc1:
        _validate_sheet_query_params(
            FormTypeEnum.FORM_2,
            "AHR",
            DirectionSchemaEnum.SUPPORT,
            None,
        )
    assert exc1.value.status_code == 400

    with pytest.raises(HTTPException) as exc2:
        _validate_sheet_query_params(
            FormTypeEnum.FORM_1,
            "SMETA",
            DirectionSchemaEnum.SUPPORT,
            None,
        )
    assert exc2.value.status_code == 400


def test_validate_sheet_query_rejects_sections_for_non_main_sheets():
    with pytest.raises(HTTPException) as exc:
        _validate_sheet_query_params(FormTypeEnum.FORM_1, "SMETA", None, ["q1"])
    assert exc.value.status_code == 400


def test_validate_sheet_query_accepts_valid_combinations():
    _validate_sheet_query_params(
        FormTypeEnum.FORM_1,
        "AHR",
        DirectionSchemaEnum.SUPPORT,
        ["plan", "q1"],
    )
    _validate_sheet_query_params(
        FormTypeEnum.FORM_2,
        "AHR",
        None,
        ["plan", "q1"],
    )


def test_parse_form3_sections_accepts_supported_values():
    assert _parse_sections("q1,q2,year") == ["q1", "q2", "year"]


def test_parse_form3_sections_rejects_invalid_values():
    with pytest.raises(HTTPException) as exc:
        _parse_sections("q1,q5")
    assert exc.value.status_code == 400
