from app.services.infra.database import get_master_db_connection
from app.services.catalog.fx import ensure_fx_table, get_rate


def test_table_is_created_and_idempotent():
    ensure_fx_table()
    ensure_fx_table()
    conn = get_master_db_connection()
    try:
        with conn.cursor() as cur:
            cur.execute("SELECT to_regclass('public.fx_rates')")
            assert cur.fetchone()[0] is not None
    finally:
        conn.close()


def test_same_currency_is_one_without_a_row():
    assert get_rate("INR", "INR") == 1.0


def test_absent_pair_returns_none():
    assert get_rate("XXX", "YYY") is None


def test_a_seeded_rate_is_read_back():
    ensure_fx_table()
    conn = get_master_db_connection()
    try:
        with conn.cursor() as cur:
            cur.execute(
                "INSERT INTO fx_rates (base_currency, quote_currency, rate) "
                "VALUES ('TST','REF',2.5) ON CONFLICT (base_currency, quote_currency) "
                "DO UPDATE SET rate = 2.5")
        conn.commit()
    finally:
        conn.close()

    assert get_rate("TST", "REF") == 2.5

    conn = get_master_db_connection()
    try:
        with conn.cursor() as cur:
            cur.execute("DELETE FROM fx_rates WHERE base_currency = 'TST'")
        conn.commit()
    finally:
        conn.close()
