import unittest

from fastapi.testclient import TestClient

from app.main import create_app


class JoinCorrespondingSumsEndpointTest(unittest.TestCase):
    def setUp(self) -> None:
        self.client = TestClient(create_app())

    def test_creates_problem_with_matching_sums(self) -> None:
        response = self.client.post(
            "/math/grade_1/join_corresponding_sums",
            json={"pair_count": 3, "seed": 1},
        )

        self.assertEqual(response.status_code, 200)
        problem = response.json()

        self.assertEqual(problem["instructions"], "Conecta.")
        self.assertEqual(len(problem["left_expressions"]), 3)
        self.assertEqual(len(problem["right_expressions"]), 3)
        self.assertEqual(len(problem["answer_key"]), 3)

        left_by_position = {
            expression["position"]: expression
            for expression in problem["left_expressions"]
        }
        right_by_position = {
            expression["position"]: expression
            for expression in problem["right_expressions"]
        }

        for expression in problem["left_expressions"] + problem["right_expressions"]:
            self.assertEqual(
                expression["first_addend"] + expression["second_addend"],
                expression["total"],
            )

        for connection in problem["answer_key"]:
            left_expression = left_by_position[connection["left_position"]]
            right_expression = right_by_position[connection["right_position"]]

            self.assertEqual(left_expression["total"], right_expression["total"])
            self.assertEqual(left_expression["total"], connection["total"])
            self.assertEqual(left_expression["match_id"], right_expression["match_id"])
            self.assertEqual(left_expression["match_id"], connection["match_id"])

    def test_returns_bad_request_for_impossible_ranges(self) -> None:
        response = self.client.post(
            "/math/grade_1/join_corresponding_sums",
            json={"pair_count": 3, "min_sum": 2, "max_sum": 2},
        )

        self.assertEqual(response.status_code, 400)
        self.assertEqual(
            response.json(),
            {"detail": "sum and addend ranges must contain enough matchable sums"},
        )


if __name__ == "__main__":
    unittest.main()
