import datetime as dt

from flyway.migration.sqlscript import SqlScriptSource, parse_inserts

SCRIPT = """CREATE TABLE [dbo].[fw_Template]( [ID] [uniqueidentifier] NOT NULL )
GO
INSERT [dbo].[fw_Template] ([ID], [Type], [Content]) VALUES (N'aa', N'LoadInPrintHeader', N'<p>It''s
two lines (with parens)</p>')
GO
INSERT [dbo].[fw_ProductBatch] ([ID], [InitialStock], [Date], [UsedByDate], [W]) VALUES (N'bb', -3, CAST(N'2025-01-22T23:16:57.527' AS DateTime), NULL, 1.5)
INSERT [dbo].[__MigrationHistory] ([Model]) VALUES (0x1F8B)
"""


def test_parse_inserts_handles_strings_casts_nulls_and_numbers():
    tables = parse_inserts(SCRIPT)
    assert tables["fw_Template"] == [{"ID": "aa", "Type": "LoadInPrintHeader",
                                      "Content": "<p>It's\ntwo lines (with parens)</p>"}]
    assert tables["fw_ProductBatch"] == [{"ID": "bb", "InitialStock": -3,
                                          "Date": dt.datetime(2025, 1, 22, 23, 16, 57, 527000),
                                          "UsedByDate": None, "W": 1.5}]
    assert tables["__MigrationHistory"] == [{"Model": b"\x1f\x8b"}]


def test_source_reads_utf16_file(tmp_path):
    path = tmp_path / "dump.sql"
    path.write_text(SCRIPT, encoding="utf-16")
    source = SqlScriptSource(path)
    assert source.rows("fw_Template")[0]["Type"] == "LoadInPrintHeader"
    assert source.rows("missing") == []
