from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session

from app.schemas.auth_schema import *

from app.core.database import get_db
from app.core.auth_deps import require_auth, AuthContext
from app.models.user_model import User
from app.services.account_service import account_auth_payload
from app.services.auth_service import (
    forgot_password_service,
    login_service,
    refresh_token_service,
    reset_password_service,
    signup_service,
    verify_forgot_otp_service,
    verify_signup_otp_service,
    user_auth_payload,
)

router = APIRouter()


@router.post("/signup")
def signup(data: SignupSchema, db: Session = Depends(get_db)):

    return signup_service(data, db)


@router.post("/verify-otp")
def verify_signup_otp(
    data: VerifyOTPSchema,
    db: Session = Depends(get_db)
):

    return verify_signup_otp_service(data, db)


@router.post("/login")
def login(
    data: LoginSchema,
    db: Session = Depends(get_db)
):

    return login_service(data, db)


@router.post("/refresh")
def refresh_token(
    data: RefreshTokenSchema,
    db: Session = Depends(get_db),
):
    return refresh_token_service(data.refresh_token, db)


@router.get("/me")
def get_me(
    auth: AuthContext = Depends(require_auth)
):
    if auth.user is not None:
        return {"data": user_auth_payload(auth.user)}

    return {"data": account_auth_payload(auth.account)}


@router.post("/forgot-password")
def forgot_password(
    data: ForgotPasswordSchema,
    db: Session = Depends(get_db)
):

    return forgot_password_service(data, db)


@router.post("/verify-forgot-otp")
def verify_forgot_otp(
    data: VerifyOTPSchema,
    db: Session = Depends(get_db)
):

    return verify_forgot_otp_service(data, db)


@router.post("/reset-password")
def reset_password(
    data: ResetPasswordSchema,
    db: Session = Depends(get_db)
):

    return reset_password_service(data, db)


# Helper schemas and endpoints for frontend integration
from pydantic import BaseModel
from app.models.otp_model import OTPVerification
from app.core.security import hash_password, verify_password

class VerifyOTPPathSchema(BaseModel):
    otp: str

class ResetPasswordPathSchema(BaseModel):
    password: str

@router.post("/verify-otp/{email}")
def verify_otp_path(
    email: str,
    data: VerifyOTPPathSchema,
    db: Session = Depends(get_db)
):
    user = db.query(User).filter(User.email == email).first()
    if not user:
        raise HTTPException(404, "User not found")

    otp = db.query(OTPVerification).filter(
        OTPVerification.user_id == user.id,
        OTPVerification.otp_code == data.otp,
        OTPVerification.is_used == False
    ).first()

    if not otp:
        raise HTTPException(400, "Invalid OTP")

    otp.is_used = True
    if otp.purpose == "signup":
        user.is_verified = True

    db.commit()
    return {
        "success": True,
        "message": "OTP verified successfully"
    }

@router.post("/reset-password/{email}")
def reset_password_path(
    email: str,
    data: ResetPasswordPathSchema,
    db: Session = Depends(get_db)
):
    user = db.query(User).filter(User.email == email).first()
    if not user:
        raise HTTPException(404, "User not found")

    if verify_password(data.password, user.password):
        raise HTTPException(400, "New password cannot be the same as the old password")

    user.password = hash_password(data.password)
    db.commit()

    return {
        "success": True,
        "message": "Password reset successful"
    }