# app/modules/orders/services/customer_order_service.py
"""
Customer-order service for managing customer-order relationships.

This service handles the orders-specific logic for customer order operations.
It follows the principle that:
- Customers module provides generic customer storage (agnostic to consumers)
- Orders module defines how it relates to customers (owns the relationship)

Similar to how:
- CMS provides generic media storage
- Catalog defines ProductMedia association
"""

import logging
from datetime import UTC, datetime

from sqlalchemy.orm import Session

from app.modules.orders.models import CustomerOrderStats, Order

logger = logging.getLogger(__name__)


class CustomerOrderService:
    """Service for customer-order operations owned by orders module."""

    def get_customer_orders(
        self,
        db: Session,
        store_id: int,
        customer_id: int,
        skip: int = 0,
        limit: int = 50,
    ) -> tuple[list[Order], int]:
        """
        Get orders for a specific customer.

        Args:
            db: Database session
            store_id: Store ID (for ownership verification)
            customer_id: Customer ID
            skip: Pagination offset
            limit: Pagination limit

        Returns:
            Tuple of (orders, total_count)
        """
        query = (
            db.query(Order)
            .filter(
                Order.customer_id == customer_id,
                Order.store_id == store_id,
            )
            .order_by(Order.created_at.desc())
        )

        total = query.count()
        orders = query.offset(skip).limit(limit).all()

        return orders, total

    def get_recent_orders(
        self,
        db: Session,
        store_id: int,
        customer_id: int,
        limit: int = 5,
    ) -> list[Order]:
        """
        Get recent orders for a customer.

        Args:
            db: Database session
            store_id: Store ID
            customer_id: Customer ID
            limit: Maximum orders to return

        Returns:
            List of recent orders
        """
        return (
            db.query(Order)
            .filter(
                Order.customer_id == customer_id,
                Order.store_id == store_id,
            )
            .order_by(Order.created_at.desc())
            .limit(limit)
            .all()
        )

    def record_order(
        self,
        db: Session,
        store_id: int,
        customer_id: int,
        total_amount_cents: int,
    ) -> CustomerOrderStats:
        """
        Record an order in customer order stats (upsert).

        Args:
            db: Database session
            store_id: Store ID
            customer_id: Customer ID
            total_amount_cents: Order total in cents

        Returns:
            Updated CustomerOrderStats
        """
        stats = (
            db.query(CustomerOrderStats)
            .filter(
                CustomerOrderStats.store_id == store_id,
                CustomerOrderStats.customer_id == customer_id,
            )
            .first()
        )
        now = datetime.now(UTC)
        if stats:
            stats.total_orders = (stats.total_orders or 0) + 1
            stats.total_spent_cents = (stats.total_spent_cents or 0) + total_amount_cents
            stats.last_order_date = now
        else:
            stats = CustomerOrderStats(
                store_id=store_id,
                customer_id=customer_id,
                total_orders=1,
                total_spent_cents=total_amount_cents,
                first_order_date=now,
                last_order_date=now,
            )
            db.add(stats)
        db.flush()
        return stats

    def get_order_count(
        self,
        db: Session,
        store_id: int,
        customer_id: int,
    ) -> int:
        """
        Get total order count for a customer.

        Args:
            db: Database session
            store_id: Store ID
            customer_id: Customer ID

        Returns:
            Total order count
        """
        return (
            db.query(Order)
            .filter(
                Order.customer_id == customer_id,
                Order.store_id == store_id,
            )
            .count()
        )


# Singleton instance
customer_order_service = CustomerOrderService()

__all__ = ["CustomerOrderService", "customer_order_service"]
