# tests/unit/models/test_customer_order_stats.py
"""Unit tests for CustomerOrderStats model."""

import pytest
from sqlalchemy.exc import IntegrityError

from app.modules.orders.models.customer_order_stats import CustomerOrderStats


@pytest.mark.unit
@pytest.mark.database
class TestCustomerOrderStatsModel:
    """Test CustomerOrderStats model."""

    def test_create_stats(self, db, test_store, test_customer):
        """Test creating customer order stats."""
        stats = CustomerOrderStats(
            store_id=test_store.id,
            customer_id=test_customer.id,
            total_orders=3,
            total_spent_cents=15000,
        )
        db.add(stats)
        db.commit()
        db.refresh(stats)

        assert stats.id is not None
        assert stats.store_id == test_store.id
        assert stats.customer_id == test_customer.id
        assert stats.total_orders == 3
        assert stats.total_spent_cents == 15000

    def test_default_values(self, db, test_store, test_customer):
        """Test default values for stats."""
        stats = CustomerOrderStats(
            store_id=test_store.id,
            customer_id=test_customer.id,
        )
        db.add(stats)
        db.commit()
        db.refresh(stats)

        assert stats.total_orders == 0
        assert stats.total_spent_cents == 0
        assert stats.last_order_date is None
        assert stats.first_order_date is None

    def test_unique_constraint(self, db, test_store, test_customer):
        """Test unique constraint on store_id + customer_id."""
        stats1 = CustomerOrderStats(
            store_id=test_store.id,
            customer_id=test_customer.id,
            total_orders=1,
        )
        db.add(stats1)
        db.commit()

        stats2 = CustomerOrderStats(
            store_id=test_store.id,
            customer_id=test_customer.id,
            total_orders=2,
        )
        db.add(stats2)
        with pytest.raises(IntegrityError):
            db.commit()

    def test_update_stats(self, db, test_store, test_customer):
        """Test updating existing stats."""
        stats = CustomerOrderStats(
            store_id=test_store.id,
            customer_id=test_customer.id,
            total_orders=1,
            total_spent_cents=5000,
        )
        db.add(stats)
        db.commit()

        stats.total_orders = 2
        stats.total_spent_cents = 12000
        db.commit()
        db.refresh(stats)

        assert stats.total_orders == 2
        assert stats.total_spent_cents == 12000
