"""
Unit tests for `repair_split_submission` merge logic (no PostgreSQL required).

DB integration for the full repair is gated on INITIATIVE_DATABASE_URL (see test_applications_db_integration.py).
"""

from __future__ import annotations

import unittest

from src.initiative_db.repair_split_submission import (
    merge_payload_for_case_repair,
    tabs_effectively_empty,
)


class RepairSplitSubmissionPureTests(unittest.TestCase):
    def test_tabs_effectively_empty_true(self) -> None:
        self.assertTrue(tabs_effectively_empty({}))
        self.assertTrue(tabs_effectively_empty({"report": {}, "application": {}, "contribution": {}}))
        self.assertTrue(tabs_effectively_empty(None))

    def test_tabs_effectively_empty_false(self) -> None:
        self.assertFalse(tabs_effectively_empty({"report": {"x": 1}}))

    def test_merge_prefers_good_tabs(self) -> None:
        good = {
            "tabs": {"application": {"initiativeName": "A"}, "report": {}, "contribution": {}},
            "caseId": "CASE-OLD",
        }
        bad = {
            "tabs": {},
            "submissionRecord": {"id": "sub-abc"},
            "submissionFile": {"url": "/submitted-initiatives/x.pdf", "type": "pdf"},
        }
        m = merge_payload_for_case_repair(
            target_case_code="CASE-OK",
            good_payload=good,
            bad_payload=bad,
        )
        self.assertEqual(m["caseId"], "CASE-OK")
        self.assertEqual(m["submissionRecord"]["id"], "sub-abc")
        self.assertEqual(m["submissionFile"]["url"], "/submitted-initiatives/x.pdf")
        self.assertEqual(m["tabs"]["application"]["initiativeName"], "A")

    def test_merge_falls_back_to_bad_tabs_when_good_empty(self) -> None:
        good = {"tabs": {}, "caseId": "CASE-OK"}
        bad = {"tabs": {"application": {"k": "v"}}, "submissionRecord": {"id": "sub-x"}}
        m = merge_payload_for_case_repair(target_case_code="CASE-OK", good_payload=good, bad_payload=bad)
        self.assertEqual(m["tabs"]["application"]["k"], "v")


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