from sqlalchemy.orm import Session
from typing import Dict, Any

from app.repositories import review_repo
from app.schemas.review_schemas import ReviewCreate, ReviewUpdate


# Сервисы отзывов
def create_review(db: Session, user_id: int, review: ReviewCreate) -> Dict[str, Any]:
    from app.schemas.review_schemas import Review as ReviewSchema
    
    new_review = review_repo.create_review(db, review, user_id)
    # Преобразуем объект SQLAlchemy в схему Pydantic
    review_schema = ReviewSchema.model_validate(new_review)
    return {"review": review_schema}


def update_review(db: Session, user_id: int, review_id: int, review: ReviewUpdate, is_admin: bool = False) -> Dict[str, Any]:
    from app.schemas.review_schemas import Review as ReviewSchema
    
    updated_review = review_repo.update_review(db, review_id, review, user_id, is_admin)
    # Преобразуем объект SQLAlchemy в схему Pydantic
    review_schema = ReviewSchema.model_validate(updated_review)
    return {"review": review_schema}


def delete_review(db: Session, user_id: int, review_id: int, is_admin: bool = False) -> Dict[str, Any]:
    success = review_repo.delete_review(db, review_id, user_id, is_admin)
    return {"success": success}


def approve_review(db: Session, review_id: int) -> Dict[str, Any]:
    from app.schemas.review_schemas import Review as ReviewSchema
    
    approved_review = review_repo.approve_review(db, review_id)
    # Преобразуем объект SQLAlchemy в схему Pydantic
    review_schema = ReviewSchema.model_validate(approved_review)
    return {"review": review_schema}


def get_product_reviews(db: Session, product_id: int, skip: int = 0, limit: int = 10) -> Dict[str, Any]:
    from app.schemas.review_schemas import Review as ReviewSchema
    
    reviews = review_repo.get_product_reviews(db, product_id, skip, limit)
    
    # Получаем рейтинг продукта
    rating = review_repo.get_product_rating(db, product_id)
    
    # Преобразуем объекты SQLAlchemy в схемы Pydantic
    reviews_schema = [ReviewSchema.model_validate(review) for review in reviews]
    
    return {
        "reviews": reviews_schema,
        "rating": rating,
        "total": rating["total_reviews"],
        "skip": skip,
        "limit": limit
    } 