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

from app.database import SessionLocal, get_db, release_db_connection
from app.dependencies import require_admin_token
from app.models import User
from app.schemas import AdminProfilePublic, AdminProfileUpdate, ChangePasswordRequest, Message
from app.security import hash_password, verify_password
from app.services.admin_profile_service import (
    ensure_admin_profile,
    save_admin_profile_image,
    serialize_admin_profile,
    set_admin_profile_image,
    update_admin_profile,
)

router = APIRouter(prefix="/profile", tags=["admin-profile"])


@router.get("", response_model=AdminProfilePublic, summary="Get admin profile")
@router.get("/get-profile", response_model=AdminProfilePublic, summary="Get admin profile (alias)")
def get_profile(db: Session = Depends(get_db), me: User = Depends(require_admin_token)):
    admin = ensure_admin_profile(db, me)
    return serialize_admin_profile(admin)


@router.patch("", response_model=AdminProfilePublic, summary="Update admin profile")
@router.patch("/update", response_model=AdminProfilePublic, include_in_schema=False)
@router.post("/update-profile", response_model=AdminProfilePublic, summary="Update admin profile")
@router.post("/update", response_model=AdminProfilePublic, include_in_schema=False)
@router.patch("/update-profile", response_model=AdminProfilePublic, include_in_schema=False)
def update_profile(
    body: AdminProfileUpdate,
    db: Session = Depends(get_db),
    me: User = Depends(require_admin_token),
):
    return update_admin_profile(db, me, body)


@router.post("/upload-image", response_model=AdminProfilePublic, summary="Upload admin profile image")
async def upload_profile_image(
    db: Session = Depends(get_db),
    me: User = Depends(require_admin_token),
    image: UploadFile = File(..., description="Profile image (jpg, png, gif, webp)"),
):
    if not image.filename:
        raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Image file is required")
    admin_id = me.id
    release_db_connection(db)
    image_path = await save_admin_profile_image(image)
    write_db = SessionLocal()
    try:
        admin = write_db.get(User, admin_id)
        if admin is None:
            raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Admin not found")
        return set_admin_profile_image(write_db, admin, image_path)
    finally:
        write_db.close()


@router.post("/change-password", response_model=Message, summary="Change logged-in admin password")
def change_password(
    body: ChangePasswordRequest,
    db: Session = Depends(get_db),
    me: User = Depends(require_admin_token),
):
    if not verify_password(body.current_password, me.hashed_password):
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="Current password is incorrect",
        )
    if body.current_password == body.new_password:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="New password must be different from current password",
        )
    me.hashed_password = hash_password(body.new_password)
    db.commit()
    return Message(message="Password updated successfully")
