import json
from fastapi import APIRouter, Depends, HTTPException, UploadFile, File, Form, Request
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
from sqlalchemy.orm import Session
from sqlalchemy import func
from sqlalchemy.exc import IntegrityError

from core.db import get_db, Poster, FeedBack
from core.crypt import decode_jwt, is_admin
from core.file import get_upload_dir, save_file, get_poster_dir, generate_file_url
from pydantic import BaseModel, EmailStr
from datetime import datetime

router = APIRouter()
security = HTTPBearer()

class Comment(BaseModel):
    user_id: int
    text: str
    rating: int

@router.post("/comment")
async def create_comment(
    comment: Comment,
    db: Session = Depends(get_db),
    credentials: HTTPAuthorizationCredentials = Depends(security),
    request: Request = None,
):
    token = credentials.credentials
    decoded_data = decode_jwt(token)
    user_id = decoded_data.get("user_id")

    if not user_id:
        raise HTTPException(status_code=401, detail="Пользователь не авторизован.")

    if comment.rating < 1 or comment.rating > 5:
        raise HTTPException(status_code=400, detail="Рейтинг должен быть от 1 до 5.")

    new_comment = FeedBack(
        userid=user_id,
        text=comment.text,
        rating=comment.rating,
        date=datetime.utcnow()
    )

    db.add(new_comment)
    db.commit()
    db.refresh(new_comment)

    return {"message": "Комментарий успешно добавлен.", "comment": new_comment}

@router.delete("/comment/{comment_id}")
async def delete_comment(
    comment_id: int,
    db: Session = Depends(get_db),
    credentials: HTTPAuthorizationCredentials = Depends(security),
):
    token = credentials.credentials
    decoded_data = decode_jwt(token)
    user_id = decoded_data.get("user_id")

    if not user_id:
        raise HTTPException(status_code=401, detail="Пользователь не авторизован.")

    comment = db.query(FeedBack).filter(FeedBack.id == comment_id, FeedBack.userid == user_id).first()

    if not comment:
        raise HTTPException(status_code=404, detail="Комментарий не найден.")
    
    if is_admin(user_id, db):
        raise HTTPException(status_code=403, detail="Недостаточно прав для выполнения этого действия.")

    db.delete(comment)
    db.commit()

    return {"message": "Комментарий успешно удален."}

@router.get("/comments")
async def get_comments(
    db: Session = Depends(get_db),
    request: Request = None,
):

    comments = db.query(FeedBack).order_by(FeedBack.date.desc()).all()

    comments_list = []
    for comment in comments:
        comments_list.append({
            "id": comment.id,
            "userid": comment.userid,
            "text": comment.text,
            "date": comment.date.isoformat(),
            "rating": comment.rating
        })
    
    return comments_list

@router.get("/average-rating")
async def get_average_rating(
    db: Session = Depends(get_db),
):
    average_rating = db.query(func.avg(FeedBack.rating)).scalar()

    if average_rating is None:
        return {"Нет рэйтинга.": "Рейтинг", "Рейтинг": 0}

    return {"Рэйтинг": round(average_rating, 2)}
