from typing import List

from fastapi import HTTPException, status
from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.orm import selectinload

from app.enums.enums import ProductStatusEnum
from app.models.listing.products import Product, ProductCategory
from app.models.user.favorite_model import UserFavorite
from app.models.user.user_model import UserAddress
from app.schemas.user.favorite_schemas import (
    FavoriteCreateRequest,
    FavoriteUpdateRequest,
    FavoriteProductSummary,
    FavoriteResponse,
)
from app.schemas.user.user_schemas import UserAddressResponse


class FavoriteService:
    def __init__(self, db: AsyncSession):
        self.db = db

    async def create_favorite(self, user_id: int, payload: FavoriteCreateRequest) -> FavoriteResponse:
        # Get and validate products - must be approved
        product_ids = list(dict.fromkeys(payload.product_ids))
        products = await self._get_products(product_ids)

        # Validate addresses
        address_ids = list(dict.fromkeys(payload.address_ids))
        addresses = await self._get_user_addresses(user_id, address_ids)

        favorite = UserFavorite(
            user_id=user_id,
            distance_value=payload.distance_value,
            distance_unit=payload.distance_unit,
            travel_mode=payload.travel_mode,
        )
        favorite.products.extend(products)
        favorite.addresses.extend(addresses)

        self.db.add(favorite)
        await self.db.commit()

        favorite = await self._load_favorite(user_id, favorite.favorite_id)
        return self._build_response(favorite)

    async def list_favorites(self, user_id: int) -> List[FavoriteResponse]:
        stmt = (
            select(UserFavorite)
            .options(
                selectinload(UserFavorite.products).selectinload(Product.category),
                selectinload(UserFavorite.addresses),
            )
            .where(UserFavorite.user_id == user_id)
            .order_by(UserFavorite.created_at.desc())
        )
        result = await self.db.execute(stmt)
        favorites = result.scalars().all()
        return [self._build_response(favorite) for favorite in favorites]

    async def update_favorite(self, user_id: int, favorite_id: int, payload: FavoriteUpdateRequest) -> FavoriteResponse:
        favorite = await self._load_favorite(user_id, favorite_id)

        if payload.distance_value is not None:
            favorite.distance_value = payload.distance_value
            favorite.distance_unit = payload.distance_unit
        elif payload.distance_unit is not None:
            favorite.distance_unit = payload.distance_unit

        if payload.travel_mode is not None:
            favorite.travel_mode = payload.travel_mode

        if payload.product_ids is not None:
            product_ids = list(dict.fromkeys(payload.product_ids))
            products = await self._get_products(product_ids)
            favorite.products.clear()
            favorite.products.extend(products)

        if payload.address_ids is not None:
            address_ids = list(dict.fromkeys(payload.address_ids))
            addresses = await self._get_user_addresses(user_id, address_ids)
            favorite.addresses.clear()
            favorite.addresses.extend(addresses)

        await self.db.commit()
        await self.db.refresh(favorite)

        return self._build_response(favorite)

    async def delete_favorite(self, user_id: int, favorite_id: int) -> dict:
        favorite = await self._load_favorite(user_id, favorite_id)

        await self.db.delete(favorite)
        await self.db.commit()

        return {"message": "Favorite removed successfully"}

    async def _load_favorite(self, user_id: int, favorite_id: int) -> UserFavorite:
        stmt = (
            select(UserFavorite)
            .options(
                selectinload(UserFavorite.products).selectinload(Product.category),
                selectinload(UserFavorite.addresses),
            )
            .where(
                UserFavorite.favorite_id == favorite_id,
                UserFavorite.user_id == user_id,
            )
        )
        result = await self.db.execute(stmt)
        favorite = result.scalar_one_or_none()

        if not favorite:
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="Favorite not found",
            )

        return favorite

    async def _get_products(self, product_ids: List[int]) -> List[Product]:
        if not product_ids:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail="At least one product_id must be provided",
            )

        stmt = (
            select(Product)
            .options(selectinload(Product.category))
            .where(
                Product.product_id.in_(product_ids),
                Product.status == ProductStatusEnum.APPROVED
            )
        )
        result = await self.db.execute(stmt)
        products = result.scalars().all()

        if len(products) != len(product_ids):
            found_ids = {p.product_id for p in products}
            missing_ids = set(product_ids) - found_ids
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail=f"One or more products are invalid or not approved: {sorted(missing_ids)}",
            )

        return products

    async def _get_user_addresses(self, user_id: int, address_ids: List[int]) -> List[UserAddress]:
        if not address_ids:
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail="At least one address_id must be provided",
            )

        stmt = select(UserAddress).where(
            UserAddress.user_id == user_id,
            UserAddress.address_id.in_(address_ids),
        )
        result = await self.db.execute(stmt)
        addresses = result.scalars().all()

        if len(addresses) != len(address_ids):
            raise HTTPException(
                status_code=status.HTTP_400_BAD_REQUEST,
                detail="One or more addresses are invalid",
            )

        return addresses

    @staticmethod
    def _build_response(favorite: UserFavorite) -> FavoriteResponse:
        product_summaries = [
            FavoriteProductSummary(
                product_id=product.product_id,
                product_name=product.product_name,
                product_description=product.product_description,
                product_image=product.product_image,
                product_barcode=product.product_barcode,
                base_price=product.base_price,
                unit=product.unit,
                category_id=product.category.category_id if product.category else None,
                category_name=product.category.category_name if product.category else None,
            )
            for product in favorite.products
        ]
        address_responses = [
            UserAddressResponse.model_validate(address) for address in favorite.addresses
        ]
        return FavoriteResponse(
            favorite_id=favorite.favorite_id,
            products=product_summaries,
            distance_value=favorite.distance_value,
            distance_unit=favorite.distance_unit,
            travel_mode=favorite.travel_mode,
            addresses=address_responses,
            created_at=favorite.created_at,
            updated_at=favorite.updated_at,
        )

