import base64
import json

from .view import (
    _build_create_view_statement,
    _extract_view_definition,
    build_view_ddl_row,
)


def test__extract_view_definition_prefers_athena_representation():
    raw_table = {
        "ViewDefinition": {
            "Representations": [
                {
                    "Dialect": "SPARK",
                    "ViewOriginalText": "SELECT * FROM spark_view",
                },
                {
                    "Dialect": "ATHENA",
                    "ViewOriginalText": "SELECT * FROM athena_view",
                },
            ]
        },
        "ViewOriginalText": "SELECT * FROM legacy_view",
    }

    assert _extract_view_definition(raw_table) == "SELECT * FROM athena_view"


def test__extract_view_definition_falls_back_to_legacy_fields():
    raw_table = {
        "ViewOriginalText": "SELECT * FROM legacy_view",
        "ViewExpandedText": "SELECT * FROM db.legacy_view",
    }

    assert _extract_view_definition(raw_table) == "SELECT * FROM legacy_view"


def test__extract_view_definition_decodes_presto_wrapper():
    payload = base64.b64encode(
        json.dumps({"originalSql": "SELECT * FROM decoded_view"}).encode(
            "utf-8"
        )
    ).decode("utf-8")
    raw_table = {
        "ViewOriginalText": f"/* Presto View: {payload} */",
    }

    assert _extract_view_definition(raw_table) == "SELECT * FROM decoded_view"


def test__build_create_view_statement_wraps_body_sql():
    assert _build_create_view_statement(
        "analytics",
        "orders_view",
        "SELECT * FROM orders",
    ) == ("CREATE VIEW analytics.orders_view AS\nSELECT * FROM orders")


def test__build_create_view_statement_keeps_existing_create_view():
    ddl = "CREATE VIEW analytics.orders_view AS\nSELECT * FROM orders"
    assert _build_create_view_statement("analytics", "orders_view", ddl) == ddl


def test_build_view_ddl_row_skips_non_views():
    assert (
        build_view_ddl_row(
            "analytics",
            {
                "Name": "orders",
                "TableType": "EXTERNAL_TABLE",
            },
        )
        is None
    )


def test_build_view_ddl_row_serializes_view():
    assert build_view_ddl_row(
        "analytics",
        {
            "Name": "orders_view",
            "TableType": "VIRTUAL_VIEW",
            "ViewOriginalText": "SELECT * FROM orders",
        },
    ) == {
        "database_name": "awsdatacatalog",
        "schema_name": "analytics",
        "view_name": "orders_view",
        "view_definition": (
            "CREATE VIEW analytics.orders_view AS\nSELECT * FROM orders"
        ),
    }
