"""Gumroad adapter: secret check, Ping parsing, refunds stub."""

from __future__ import annotations

from decimal import Decimal

import pytest

from app.adapters.gumroad import GumroadAdapter, UnmappedProductError


def _sale_payload(**overrides) -> dict:
    base = {
        "sale_id": "GUM-1001",
        "email": "jane@example.com",
        "full_name": "Jane Doe",
        "product_id": "datatools-core",
        "price": "9900",          # cents
        "currency": "usd",
        "offer_code": "",
        "test": "false",
    }
    base.update(overrides)
    return base


def test_verify_secret_correct():
    a = GumroadAdapter(secret="abc123")
    assert a.verify_secret("abc123") is True


def test_verify_secret_wrong():
    a = GumroadAdapter(secret="abc123")
    assert a.verify_secret("nope") is False


def test_verify_secret_unset_rejects_all():
    a = GumroadAdapter(secret=None)
    assert a.verify_secret("anything") is False
    assert a.verify_secret(None) is False


def test_verify_secret_missing_presented_value():
    a = GumroadAdapter(secret="abc123")
    assert a.verify_secret(None) is False
    assert a.verify_secret("") is False


def test_parse_sale_happy_path():
    a = GumroadAdapter(secret="x")
    sale = a.parse_sale(_sale_payload())
    assert sale is not None
    assert sale.source == "gumroad"
    assert sale.source_order_id == "GUM-1001"
    assert sale.buyer_email == "jane@example.com"
    assert sale.buyer_name == "Jane Doe"
    assert sale.tier == "core"
    assert sale.years == 1
    assert sale.amount_paid == Decimal("99.00")
    assert sale.currency == "USD"
    assert sale.promotion is None


def test_parse_sale_with_offer_code():
    a = GumroadAdapter(secret="x")
    sale = a.parse_sale(_sale_payload(offer_code="LAUNCH50"))
    assert sale.promotion == "LAUNCH50"


def test_parse_sale_test_ping_tagged():
    a = GumroadAdapter(secret="x")
    sale = a.parse_sale(_sale_payload(test="true"))
    assert sale.notes == "gumroad test ping"


def test_parse_sale_name_fallback_from_email():
    a = GumroadAdapter(secret="x")
    sale = a.parse_sale(_sale_payload(full_name="", email="john.doe@example.com"))
    assert sale.buyer_name == "John Doe"


def test_parse_sale_missing_required_returns_none():
    a = GumroadAdapter(secret="x")
    assert a.parse_sale(_sale_payload(sale_id="")) is None
    assert a.parse_sale(_sale_payload(email="")) is None
    assert a.parse_sale(_sale_payload(product_id="")) is None


def test_parse_sale_unmapped_product_raises():
    a = GumroadAdapter(secret="x")
    with pytest.raises(UnmappedProductError):
        a.parse_sale(_sale_payload(product_id="no-such-sku"))


def test_parse_refund_stub_returns_none():
    a = GumroadAdapter(secret="x")
    assert a.parse_refund({"any": "payload"}) is None
