from sqlalchemy.orm import Session
from fastapi import HTTPException, status
from typing import Dict, Any, Optional
from datetime import datetime

from app.repositories import content_repo
from app.schemas.content_schemas import PageCreate, PageUpdate, AnalyticsLogCreate


# Сервисы информационных страниц
def create_page(db: Session, page: PageCreate) -> Dict[str, Any]:
    new_page = content_repo.create_page(db, page)
    return {"page": new_page}


def update_page(db: Session, page_id: int, page: PageUpdate) -> Dict[str, Any]:
    updated_page = content_repo.update_page(db, page_id, page)
    return {"page": updated_page}


def delete_page(db: Session, page_id: int) -> Dict[str, Any]:
    success = content_repo.delete_page(db, page_id)
    return {"success": success}


def get_page_by_slug(db: Session, slug: str) -> Dict[str, Any]:
    page = content_repo.get_page_by_slug(db, slug)
    if not page:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="Страница не найдена"
        )
    
    return {"page": page}


# Сервисы аналитики
def log_event(db: Session, log: AnalyticsLogCreate) -> Dict[str, Any]:
    new_log = content_repo.log_analytics_event(db, log)
    return {"log": new_log}


def get_analytics_report(
    db: Session, 
    period: str = "day",
    start_date: Optional[datetime] = None,
    end_date: Optional[datetime] = None
) -> Dict[str, Any]:
    report = content_repo.get_analytics_report(db, period, start_date, end_date)
    return {"report": report} 