from fastapi import APIRouter, Depends, HTTPException, status
from app.controllers.app_user import app_user_controller
from app.schemas.app_user import (
    AppUserRegisterSchema, 
    AppUserLoginSchema,
    AppUserJWTOut,
    AppUserInfoOut,
    AppUserUpdateSchema,
    AppUserChangePasswordSchema
)
from app.utils.app_user_jwt import (
    create_app_user_access_token,
    get_current_app_user,
    ACCESS_TOKEN_EXPIRE_MINUTES
)
from app.models.user import AppUser

router = APIRouter()


@router.post("/register", response_model=dict, summary="用户注册")
async def register(
    register_data: AppUserRegisterSchema
):
    """
    用户注册 - 只需要手机号
    默认密码为手机号后六位
    """
    try:
        user = await app_user_controller.register(register_data)
        return {
            "code": 200,
            "message": "注册成功",
            "data": {
                "user_id": user.id,
                "phone": user.phone,
                "default_password": register_data.phone[-6:]  # 返回默认密码供用户知晓
            }
        }
    except Exception as e:
        raise HTTPException(status_code=400, detail=str(e))


@router.post("/login", response_model=AppUserJWTOut, summary="用户登录")
async def login(
    login_data: AppUserLoginSchema
):
    """
    用户登录
    """
    user = await app_user_controller.authenticate(login_data)
    if not user:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="手机号或密码错误"
        )
    
    # 更新最后登录时间
    await app_user_controller.update_last_login(user.id)
    
    # 生成访问令牌
    access_token = create_app_user_access_token(user.id, user.phone)
    
    return AppUserJWTOut(
        access_token=access_token,
        token_type="bearer",
        expires_in=ACCESS_TOKEN_EXPIRE_MINUTES * 60
    )


@router.post("/logout", summary="用户登出")
async def logout(current_user: AppUser = Depends(get_current_app_user)):
    """
    用户登出（客户端需要删除本地token）
    """
    return {"code": 200, "message": "登出成功"}


@router.get("/profile", response_model=AppUserInfoOut, summary="获取用户信息")
async def get_profile(current_user: AppUser = Depends(get_current_app_user)):
    """
    获取当前用户信息
    """
    return current_user


@router.put("/profile", response_model=AppUserInfoOut, summary="更新用户信息")
async def update_profile(
    update_data: AppUserUpdateSchema,
    current_user: AppUser = Depends(get_current_app_user)
):
    """
    更新用户信息
    """
    updated_user = await app_user_controller.update_user_info(current_user.id, update_data)
    if not updated_user:
        raise HTTPException(status_code=404, detail="用户不存在")
    
    return updated_user


@router.post("/change-password", summary="修改密码")
async def change_password(
    password_data: AppUserChangePasswordSchema,
    current_user: AppUser = Depends(get_current_app_user)
):
    """
    修改密码
    """
    success = await app_user_controller.change_password(
        current_user.id, 
        password_data.old_password, 
        password_data.new_password
    )
    
    if not success:
        raise HTTPException(status_code=400, detail="原密码错误")
    
    return {"code": 200, "message": "密码修改成功"}


@router.get("/validate-token", summary="验证token")
async def validate_token(current_user: AppUser = Depends(get_current_app_user)):
    """
    验证token是否有效
    """
    return {
        "code": 200,
        "message": "token有效",
        "data": {
            "user_id": current_user.id,
            "phone": current_user.phone
        }
    }