from fastapi import APIRouter, Depends, HTTPException, status, Body
from sqlalchemy.orm import Session
from app.schemas.user import UserOut, UserCreate, UserUpdate, UserRole
from app.models.user import User
from app.core.database import SessionLocal
from passlib.context import CryptContext
from typing import List

router = APIRouter(prefix="/users", tags=["users"])
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")

def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()

# — Endpoints —

@router.get("/", response_model=List[UserOut])
def list_users(db: Session = Depends(get_db)):
    return db.query(User).all()

@router.get("/{user_id}", response_model=UserOut)
def get_user(user_id: int, db: Session = Depends(get_db)):
    user = db.query(User).filter(User.id == user_id).first()
    if not user:
        raise HTTPException(status_code=404, detail="User not found")
    return user

@router.post("/", response_model=UserOut, status_code=status.HTTP_201_CREATED)
def create_user(user: UserCreate, db: Session = Depends(get_db)):
    if db.query(User).filter(User.email == user.email).first():
        raise HTTPException(status_code=409, detail="E-Mail already exists")
    if user.alias and db.query(User).filter(User.alias == user.alias).first():
        raise HTTPException(status_code=409, detail="Alias already exists")
    hashed_password = pwd_context.hash(user.password)
    hashed_pin = pwd_context.hash(user.pin)
    db_user = User(
        name=user.name,
        email=user.email,
        hashed_password=hashed_password,
        hashed_pin=hashed_pin,
        alias=user.alias,
        paypal_email=user.paypal_email,
        role=user.role,
        is_active=True
    )
    db.add(db_user)
    db.commit()
    db.refresh(db_user)
    return db_user

@router.patch("/{user_id}", response_model=UserOut)
def update_user(user_id: int, user: UserUpdate, db: Session = Depends(get_db)):
    db_user = db.query(User).filter(User.id == user_id).first()
    if not db_user:
        raise HTTPException(status_code=404, detail="User not found")
    # ... (bestehende Update-Logik) ...
    db.commit()
    db.refresh(db_user)
    return db_user

@router.delete("/{user_id}", status_code=status.HTTP_204_NO_CONTENT)
def delete_user(user_id: int, db: Session = Depends(get_db)):
    db_user = db.query(User).filter(User.id == user_id).first()
    if not db_user:
        raise HTTPException(status_code=404, detail="User not found")
    db.delete(db_user)
    db.commit()

# — NEU: PIN-Login endpoint —
@router.post("/login/pin", response_model=UserOut)
def login_with_pin(pin: str = Body(...), db: Session = Depends(get_db)):
    # alle aktiven User laden und PIN gegen hashed_pin prüfen
    users = db.query(User).filter(User.is_active == True).all()
    for u in users:
        if pwd_context.verify(pin, u.hashed_pin):
            return u
    raise HTTPException(status_code=401, detail="Invalid PIN")
