from fastapi import APIRouter, Request, Depends, HTTPException
from fastapi.responses import JSONResponse
from pydantic import BaseModel
from typing import Optional
from backend.services.auth_service import auth_service

router = APIRouter()

class RegisterRequest(BaseModel):
    username: str
    password: str
    is_admin: Optional[bool] = False

class LoginRequest(BaseModel):
    username: str
    password: str

class UpdateUserRequest(BaseModel):
    username: Optional[str] = None
    password: Optional[str] = None
    is_admin: Optional[bool] = None
    is_active: Optional[bool] = None

@router.post("/register")
def register(req: RegisterRequest):
    result = auth_service.register_user(req.username, req.password, req.is_admin)
    if not result["success"]:
        raise HTTPException(status_code=400, detail=result["error"])
    return result

@router.post("/login")
def login(req: LoginRequest):
    result = auth_service.login_user(req.username, req.password)
    if not result["success"]:
        raise HTTPException(status_code=401, detail=result["error"])
    return result

@router.post("/logout")
def logout(token: str):
    result = auth_service.logout_user(token)
    if not result["success"]:
        raise HTTPException(status_code=401, detail=result["error"])
    return result

@router.get("/user/{user_id}")
def get_user_info(user_id: int):
    result = auth_service.get_user_info(user_id)
    if not result["success"]:
        raise HTTPException(status_code=404, detail=result["error"])
    return result

@router.put("/user/{user_id}")
def update_user_info(user_id: int, req: UpdateUserRequest):
    result = auth_service.update_user_info(user_id, **req.dict(exclude_unset=True))
    if not result["success"]:
        raise HTTPException(status_code=400, detail=result["error"])
    return result

@router.delete("/user/{user_id}")
def delete_user(user_id: int):
    result = auth_service.delete_user(user_id)
    if not result["success"]:
        raise HTTPException(status_code=400, detail=result["error"])
    return result 