from app.jobs.repair_gala_x_y_titles import (
    fix_gala_x_y_slug,
    fix_gala_x_y_text,
    repair_title_and_slug,
    _candidate_for_product,
)
from db.models import MasterProduct


def test_fix_gala_x_y_text_restores_galaxy():
    assert fix_gala_x_y_text("BH09 B09FD - Gala x y Horizon - Fabuwood - Base") == (
        "BH09 B09FD - Galaxy Horizon - Fabuwood - Base"
    )
    assert fix_gala_x_y_text("Gala  x  y Horizon") == "Galaxy Horizon"
    assert fix_gala_x_y_text("gala x y") == "Galaxy"
    assert fix_gala_x_y_text("Galaxy Horizon") is None
    assert fix_gala_x_y_text("12 x 24 Base") is None


def test_fix_gala_x_y_slug():
    assert (
        fix_gala_x_y_slug("bh09-b09fd-gala-x-y-horizon-fabuwood-base-fgh-b09fd")
        == "bh09-b09fd-galaxy-horizon-fabuwood-base-fgh-b09fd"
    )
    assert fix_gala_x_y_slug("galaxy-horizon-fgh-b09fd") is None


def test_repair_title_and_slug_rebuilds_pdp():
    out = repair_title_and_slug(
        "BH09 B09FD - Gala x y Horizon - Fabuwood - Base",
        "FGH-B09FD",
        existing_slug="bh09-b09fd-gala-x-y-horizon-fabuwood-base-fgh-b09fd",
    )
    assert out["name"] == "BH09 B09FD - Galaxy Horizon - Fabuwood - Base"
    assert "gala-x-y" not in out["url_key"]
    assert out["url_key"].endswith("-fgh-b09fd")
    assert "galaxy-horizon" in out["url_key"]


def test_candidate_for_product_detects_corrupted_name():
    product = MasterProduct()
    product.sku = "FGH-B09FD"
    product.name = "BH09 B09FD - Gala x y Horizon - Fabuwood - Base"
    product.collection = "Galaxy Horizon"
    product.raw_payload = {
        "meta_title": "BH09 B09FD - Gala x y Horizon - Fabuwood - Base",
        "product_url_slug": "bh09-b09fd-gala-x-y-horizon-fabuwood-base-fgh-b09fd",
    }
    product.is_active = True

    candidate = _candidate_for_product(product, attrs={}, overrides={})
    assert candidate is not None
    assert candidate.new_name == "BH09 B09FD - Galaxy Horizon - Fabuwood - Base"
    assert "gala-x-y" not in candidate.new_url_key
    assert "name" in candidate.fields_touched


def test_candidate_skips_clean_galaxy_title():
    product = MasterProduct()
    product.sku = "FGH-B12"
    product.name = "B12 - Galaxy Horizon - Fabuwood - Base"
    product.collection = "Galaxy Horizon"
    product.raw_payload = {}
    product.is_active = True

    assert _candidate_for_product(product, attrs={}, overrides={}) is None
