from pathlib import Path
import unittest


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


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

        for required in (
            "current_database() <> 'booking_test'",
            "ARR migrations 008 through 012 must be applied first",
            "ADD COLUMN uploaded_filename text",
            "processing_runs_uploaded_filename_check",
            "uploaded_filename IS NULL",
            "right(lower(uploaded_filename), 4) = '.xml'",
            "Internal source artifacts remain source.xml",
        ):
            with self.subTest(required=required):
                self.assertIn(required, sql)

        self.assertNotIn("UPDATE ingestion.processing_runs", sql)
        self.assertNotIn("source.original_filename", sql)

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

        self.assertIn("current_database() <> 'booking_test'", sql)
        self.assertIn("WHERE uploaded_filename IS NOT NULL", sql)
        self.assertIn(
            "refusing rollback: uploaded filename provenance exists",
            sql,
        )
        self.assertIn("DROP COLUMN uploaded_filename", sql)


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