"""The COPY-aware schema-qualifier rewrite is the one piece of the nightly
snapshot that can silently corrupt data if wrong — pin its behavior."""

from scripts.nightly_snapshot import rewrite_sql


def test_rewrites_ddl_but_never_copy_data():
    dump = [
        "CREATE TABLE public.time_entries (id uuid);\n",
        "ALTER TABLE ONLY auth.users ALTER COLUMN id SET NOT NULL;\n",
        "COPY public.time_entries (id, note) FROM stdin;\n",
        "row1\tsee public.site and auth.users for details\n",
        "\\.\n",
        "SELECT pg_catalog.setval('public.entries_id_seq', 42, true);\n",
    ]
    out = list(rewrite_sql(dump))
    assert out[0] == "CREATE TABLE legacy.time_entries (id uuid);\n"
    assert out[1] == "ALTER TABLE ONLY legacy.users ALTER COLUMN id SET NOT NULL;\n"
    assert out[2] == "COPY legacy.time_entries (id, note) FROM stdin;\n"
    assert out[3] == dump[3]  # data inside the COPY block is byte-identical
    assert out[4] == "\\.\n"
    # rewriting resumes after the COPY terminator (setval targets the sequence)
    assert out[5] == "SELECT pg_catalog.setval('legacy.entries_id_seq', 42, true);\n"


def test_schema_level_statements_are_skipped():
    out = list(rewrite_sql(["CREATE SCHEMA public;\n", "COMMENT ON SCHEMA public IS 'x';\n"]))
    assert all(line.startswith("-- [snapshot] skipped:") for line in out)
