from pathlib import Path
import unittest


PROJECT_ROOT = Path(__file__).resolve().parents[1]
UP_PATH = PROJECT_ROOT / "database" / "011_artifact_object_identity.sql"
DOWN_PATH = PROJECT_ROOT / "database" / "011_artifact_object_identity.down.sql"


class ArtifactObjectIdentityMigrationTests(unittest.TestCase):
    def test_forward_migration_replaces_content_uniqueness_with_lookup_index(self) -> None:
        sql = UP_PATH.read_text(encoding="utf-8")

        self.assertIn("current_database() <> 'booking_test'", sql)
        self.assertIn("DROP CONSTRAINT artifacts_kind_hash_unique", sql)
        self.assertIn("CREATE INDEX artifacts_kind_hash_idx", sql)
        self.assertNotIn("CREATE UNIQUE INDEX artifacts_kind_hash_idx", sql)
        self.assertNotIn("DROP SCHEMA", sql)

    def test_rollback_refuses_after_repeated_content_is_registered(self) -> None:
        sql = DOWN_PATH.read_text(encoding="utf-8")

        self.assertIn("current_database() <> 'booking_test'", sql)
        self.assertIn("GROUP BY artifact_kind, sha256", sql)
        self.assertIn("HAVING count(*) > 1", sql)
        self.assertIn(
            "refusing rollback: repeated artifact content exists across storage identities",
            sql,
        )
        self.assertIn("ADD CONSTRAINT artifacts_kind_hash_unique", sql)


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