# tests/unit/models/database/test_marketplace_product.py
"""Unit tests for MarketplaceProduct database model."""

import pytest
from sqlalchemy.exc import IntegrityError

from app.modules.marketplace.models import (
    MarketplaceProduct,
    MarketplaceProductTranslation,
)


def _create_with_translation(db, marketplace_product_id, title, **kwargs):
    """Helper to create MarketplaceProduct with translation."""
    mp = MarketplaceProduct(marketplace_product_id=marketplace_product_id, **kwargs)
    db.add(mp)
    db.flush()

    translation = MarketplaceProductTranslation(
        marketplace_product_id=mp.id,
        language="en",
        title=title,
    )
    db.add(translation)
    db.commit()
    db.refresh(mp)
    return mp


@pytest.mark.unit
@pytest.mark.database
class TestMarketplaceProductModel:
    """Test MarketplaceProduct model."""

    def test_marketplace_product_creation(self, db):
        """Test MarketplaceProduct model creation."""
        marketplace_product = _create_with_translation(
            db,
            marketplace_product_id="DB_TEST_001",
            title="Database Test Product",
            price="25.99",
            currency="USD",
            brand="DBTest",
            gtin="1234567890123",
            availability="in stock",
            marketplace="Letzshop",
            store_name="Test Store",
        )

        assert marketplace_product.id is not None
        assert marketplace_product.marketplace_product_id == "DB_TEST_001"
        assert marketplace_product.get_title("en") == "Database Test Product"
        assert marketplace_product.marketplace == "Letzshop"
        assert marketplace_product.created_at is not None

    def test_marketplace_product_id_uniqueness(self, db):
        """Test unique marketplace_product_id constraint."""
        _create_with_translation(
            db,
            marketplace_product_id="UNIQUE_001",
            title="Product 1",
            marketplace="Letzshop",
        )

        # Duplicate marketplace_product_id should raise error
        with pytest.raises(IntegrityError):
            _create_with_translation(
                db,
                marketplace_product_id="UNIQUE_001",
                title="Product 2",
                marketplace="Letzshop",
            )

    def test_marketplace_product_all_fields(self, db):
        """Test MarketplaceProduct with all optional fields."""
        marketplace_product = _create_with_translation(
            db,
            marketplace_product_id="FULL_001",
            title="Full Product",
            link="https://example.com/product",
            image_link="https://example.com/image.jpg",
            availability="in stock",
            price="99.99",
            brand="TestBrand",
            gtin="9876543210123",
            mpn="MPN123",
            condition="new",
            adult="no",
            age_group="adult",
            color="blue",
            gender="unisex",
            material="cotton",
            pattern="solid",
            size="M",
            google_product_category="Apparel & Accessories",
            product_type_raw="Clothing",
            currency="EUR",
            marketplace="Letzshop",
            store_name="Full Store",
        )

        assert marketplace_product.brand == "TestBrand"
        assert marketplace_product.gtin == "9876543210123"
        assert marketplace_product.color == "blue"
        assert marketplace_product.size == "M"

    def test_marketplace_product_custom_labels(self, db):
        """Test MarketplaceProduct with custom labels."""
        marketplace_product = _create_with_translation(
            db,
            marketplace_product_id="LABELS_001",
            title="Labeled Product",
            marketplace="Letzshop",
            custom_label_0="Label0",
            custom_label_1="Label1",
            custom_label_2="Label2",
            custom_label_3="Label3",
            custom_label_4="Label4",
        )

        assert marketplace_product.custom_label_0 == "Label0"
        assert marketplace_product.custom_label_4 == "Label4"

    def test_marketplace_product_minimal_fields(self, db):
        """Test MarketplaceProduct with only required fields."""
        marketplace_product = _create_with_translation(
            db,
            marketplace_product_id="MINIMAL_001",
            title="Minimal Product",
        )

        assert marketplace_product.id is not None
        assert marketplace_product.marketplace_product_id == "MINIMAL_001"
        assert marketplace_product.get_title("en") == "Minimal Product"
        assert marketplace_product.get_description("en") is None
        assert marketplace_product.price is None

    def test_marketplace_product_digital_fields(self, db):
        """Test MarketplaceProduct with digital product fields."""
        marketplace_product = _create_with_translation(
            db,
            marketplace_product_id="DIGITAL_001",
            title="Digital Product",
            product_type_enum="digital",
            is_digital=True,
            digital_delivery_method="license_key",
            platform="steam",
            region_restrictions=["EU", "US"],
            license_type="single_use",
        )

        assert marketplace_product.product_type_enum == "digital"
        assert marketplace_product.is_digital is True
        assert marketplace_product.digital_delivery_method == "license_key"
        assert marketplace_product.platform == "steam"
        assert marketplace_product.region_restrictions == ["EU", "US"]
        assert marketplace_product.license_type == "single_use"

    def test_marketplace_product_translation_methods(self, db):
        """Test translation helper methods."""
        mp = MarketplaceProduct(marketplace_product_id="TRANS_001")
        db.add(mp)
        db.flush()

        # Add English translation
        en_trans = MarketplaceProductTranslation(
            marketplace_product_id=mp.id,
            language="en",
            title="English Title",
            description="English Description",
        )
        db.add(en_trans)

        # Add French translation
        fr_trans = MarketplaceProductTranslation(
            marketplace_product_id=mp.id,
            language="fr",
            title="Titre Français",
            description="Description Française",
        )
        db.add(fr_trans)
        db.commit()
        db.refresh(mp)

        assert mp.get_title("en") == "English Title"
        assert mp.get_title("fr") == "Titre Français"
        assert mp.get_description("en") == "English Description"
        assert mp.get_description("fr") == "Description Française"

        # Test fallback to English for unknown language
        assert mp.get_title("de") == "English Title"  # Falls back to 'en'
        assert mp.get_description("de") == "English Description"

    def test_marketplace_product_numeric_prices(self, db):
        """Test numeric price fields."""
        marketplace_product = _create_with_translation(
            db,
            marketplace_product_id="PRICES_001",
            title="Priced Product",
            price="99.99 EUR",
            price_numeric=99.99,
            sale_price="79.99 EUR",
            sale_price_numeric=79.99,
        )

        assert marketplace_product.price == "99.99 EUR"
        assert marketplace_product.price_numeric == 99.99
        assert marketplace_product.sale_price_numeric == 79.99
        assert marketplace_product.effective_price == 99.99
        assert marketplace_product.effective_sale_price == 79.99

    def test_marketplace_product_attributes_json(self, db):
        """Test flexible attributes JSON field."""
        marketplace_product = _create_with_translation(
            db,
            marketplace_product_id="ATTRS_001",
            title="Product with Attributes",
            attributes={
                "custom_field": "custom_value",
                "nested": {"key": "value"},
            },
        )

        assert marketplace_product.attributes["custom_field"] == "custom_value"
        assert marketplace_product.attributes["nested"]["key"] == "value"

    def test_marketplace_product_all_images_property(self, db):
        """Test all_images property."""
        marketplace_product = _create_with_translation(
            db,
            marketplace_product_id="IMAGES_001",
            title="Product with Images",
            image_link="https://example.com/main.jpg",
            additional_images=[
                "https://example.com/img1.jpg",
                "https://example.com/img2.jpg",
            ],
        )

        images = marketplace_product.all_images
        assert len(images) == 3
        assert images[0] == "https://example.com/main.jpg"
        assert "https://example.com/img1.jpg" in images
        assert "https://example.com/img2.jpg" in images
