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

from database import get_db
from model.doctor import Doctor
from model.center import Center
from core.security import verify_password
from schemas import DoctorLogin, DoctorLoginOut

router = APIRouter(prefix="/doctor", tags=["Doctor Auth"])


@router.post("/login", response_model=DoctorLoginOut)
def doctor_login(payload: DoctorLogin, db: Session = Depends(get_db)):
    doctor = db.query(Doctor).filter(Doctor.username == payload.username).first()

    if not doctor or not verify_password(payload.password, doctor.password):
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Invalid username or password",
        )
    if not doctor.is_active:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="This account has been deactivated",
        )

    center = db.get(Center, doctor.center_id)
    # Build the response explicitly so we can add the center name.
    return DoctorLoginOut(
        id=doctor.id,
        full_name=doctor.full_name,
        username=doctor.username,
        email=doctor.email,
        specialization=doctor.specialization,
        center_id=doctor.center_id,
        center_name=center.name if center else None,
    )
