from fastapi import APIRouter, Depends, HTTPException, status
from fastapi.security import OAuth2PasswordRequestForm
from sqlalchemy.orm import Session
from typing import Dict, Any

from app.core import get_db, get_current_user
from app import services
from app.schemas.user_schemas import UserCreate, Token, PasswordReset, PasswordChange, User

# Роутер для аутентификации
auth_router = APIRouter(prefix="/auth", tags=["Аутентификация"])

@auth_router.post("/register", response_model=Dict[str, Any])
async def register(user: UserCreate, db: Session = Depends(get_db)):
    return services.register_user(db, user)


@auth_router.post("/login", response_model=Token)
async def login_for_access_token(form_data: OAuth2PasswordRequestForm = Depends(), db: Session = Depends(get_db)):
    # Примечание: form_data.username на самом деле содержит email пользователя
    # OAuth2PasswordRequestForm использует поле username, но мы используем его для email
    result = services.login_user(db, form_data.username, form_data.password)
    return result


@auth_router.post("/reset-password", response_model=Dict[str, Any])
async def reset_password(reset_data: PasswordReset, db: Session = Depends(get_db)):
    """Запрос на сброс пароля"""
    return services.request_password_reset(db, reset_data.email)


@auth_router.post("/set-new-password", response_model=Dict[str, Any])
async def set_new_password(token: str, password: str, db: Session = Depends(get_db)):
    """Установка нового пароля по токену сброса"""
    return services.reset_password(db, token, password)


@auth_router.post("/change-password", response_model=Dict[str, Any])
async def change_password(
    password_data: PasswordChange, 
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """Изменение пароля авторизованным пользователем"""
    return services.change_password(
        db, 
        current_user.id, 
        password_data.current_password, 
        password_data.new_password
    ) 