import pytest
from psycopg2.extras import Json

from app.services.infra.database import bootstrap_tenant, get_db_connection
from app.services.pairing.candidates import load_eligible


def _insert(schema, key, name, content_hash, in_stock=True, missing_fields=None,
            attributes=None):
    conn = get_db_connection()
    try:
        with conn.cursor() as cur:
            cur.execute(
                f'INSERT INTO "{schema}".strategist_products '
                "(product_key, name, product_url, price_cents, content_hash, "
                " in_stock, missing_fields, attributes) "
                "VALUES (%s,%s,%s,%s,%s,%s,%s,%s)",
                (key, name, f"https://x.example/{key}", 1000, content_hash,
                 in_stock, missing_fields or [], Json(attributes or [])))
        conn.commit()
    finally:
        conn.close()


@pytest.fixture
def catalog(temp_tenant):
    bootstrap_tenant(temp_tenant)
    _insert(temp_tenant, "p:1", "Oxford Shirt", "hash-1",
            attributes=[{"key": "color", "value": "white"}])
    _insert(temp_tenant, "p:2", "Out Of Stock Shirt", "hash-2", in_stock=False,
            attributes=[{"key": "color", "value": "black"}])
    _insert(temp_tenant, "p:3", "Missing Field Shirt", "hash-3",
            missing_fields=["product_url"],
            attributes=[{"key": "color", "value": "blue"}])
    _insert(temp_tenant, "p:4", "No Attributes Shirt", "hash-4", attributes=[])
    return temp_tenant


def test_load_eligible_returns_only_the_normal_product(catalog):
    eligible = load_eligible(catalog)
    assert [p["product_key"] for p in eligible] == ["p:1"]
