from datetime import datetime
from fastapi import APIRouter
from psycopg2.extras import RealDictCursor

from auth import create_access_token
from database import ensure_user_table, get_db_connection, hash_password, password_needs_rehash, verify_password
from schemas import UserCreate, UserLogin, UserUpdate

router = APIRouter()


@router.get("/api/users")
def get_users():
    ensure_user_table()
    conn = get_db_connection()
    cursor = conn.cursor(cursor_factory=RealDictCursor)
    try:
        cursor.execute("""
            SELECT id, username, real_name, role, email, is_active, created_at, last_login
            FROM sys_users
            ORDER BY created_at ASC, id ASC
        """)
        return {"status": "success", "data": cursor.fetchall()}
    except Exception as exc:
        return {"status": "error", "message": str(exc)}
    finally:
        cursor.close()
        conn.close()


@router.get("/api/users/{user_id}")
def get_user(user_id: int):
    ensure_user_table()
    conn = get_db_connection()
    cursor = conn.cursor(cursor_factory=RealDictCursor)
    try:
        cursor.execute("""
            SELECT id, username, real_name, role, email, is_active, created_at, last_login
            FROM sys_users
            WHERE id = %s
        """, (user_id,))
        user = cursor.fetchone()
        if not user:
            return {"status": "error", "message": "用户不存在"}
        return {"status": "success", "data": user}
    except Exception as exc:
        return {"status": "error", "message": str(exc)}
    finally:
        cursor.close()
        conn.close()


@router.post("/api/users/login")
def login(item: UserLogin):
    ensure_user_table()
    conn = get_db_connection()
    cursor = conn.cursor(cursor_factory=RealDictCursor)
    try:
        cursor.execute("""
            SELECT id, username, real_name, role, email, is_active, created_at, last_login, password_hash
            FROM sys_users
            WHERE username = %s
        """, (item.username,))
        user = cursor.fetchone()
        if not user or not verify_password(item.password, user["password_hash"]):
            return {"status": "error", "message": "用户名或密码错误"}
        if not user["is_active"]:
            return {"status": "error", "message": "账户已禁用"}

        now = datetime.now()
        if password_needs_rehash(user["password_hash"]):
            cursor.execute(
                "UPDATE sys_users SET last_login = %s, password_hash = %s WHERE id = %s",
                (now, hash_password(item.password), user["id"]),
            )
        else:
            cursor.execute("UPDATE sys_users SET last_login = %s WHERE id = %s", (now, user["id"]))
        conn.commit()
        user["last_login"] = now
        user.pop("password_hash", None)
        token = create_access_token(user["id"], user["username"], user["role"])
        return {"status": "success", "message": "登录成功", "data": user, "access_token": token, "token_type": "bearer"}
    except Exception as exc:
        conn.rollback()
        return {"status": "error", "message": str(exc)}
    finally:
        cursor.close()
        conn.close()


@router.post("/api/users")
def create_user(item: UserCreate):
    ensure_user_table()
    conn = get_db_connection()
    cursor = conn.cursor()
    try:
        cursor.execute("SELECT 1 FROM sys_users WHERE username = %s", (item.username,))
        if cursor.fetchone():
            return {"status": "error", "message": "用户名已存在"}

        cursor.execute("""
            INSERT INTO sys_users (username, password_hash, real_name, role, email, is_active)
            VALUES (%s, %s, %s, %s, %s, %s)
        """, (
            item.username,
            hash_password(item.password),
            item.real_name,
            item.role,
            item.email,
            item.is_active
        ))
        conn.commit()
        return {"status": "success", "message": "用户创建成功"}
    except Exception as exc:
        conn.rollback()
        return {"status": "error", "message": str(exc)}
    finally:
        cursor.close()
        conn.close()


@router.put("/api/users/{user_id}")
def update_user(user_id: int, item: UserUpdate):
    ensure_user_table()
    conn = get_db_connection()
    cursor = conn.cursor()
    try:
        cursor.execute("SELECT 1 FROM sys_users WHERE username = %s AND id <> %s", (item.username, user_id))
        if cursor.fetchone():
            return {"status": "error", "message": "用户名已存在"}

        if item.password:
            cursor.execute("""
                UPDATE sys_users
                SET username = %s, real_name = %s, role = %s, email = %s, is_active = %s, password_hash = %s
                WHERE id = %s
            """, (
                item.username,
                item.real_name,
                item.role,
                item.email,
                item.is_active,
                hash_password(item.password),
                user_id
            ))
        else:
            cursor.execute("""
                UPDATE sys_users
                SET username = %s, real_name = %s, role = %s, email = %s, is_active = %s
                WHERE id = %s
            """, (
                item.username,
                item.real_name,
                item.role,
                item.email,
                item.is_active,
                user_id
            ))
        conn.commit()
        return {"status": "success", "message": "用户更新成功"}
    except Exception as exc:
        conn.rollback()
        return {"status": "error", "message": str(exc)}
    finally:
        cursor.close()
        conn.close()


@router.delete("/api/users/{user_id}")
def delete_user(user_id: int):
    if user_id == 1:
        return {"status": "error", "message": "默认管理员不可删除"}

    ensure_user_table()
    conn = get_db_connection()
    cursor = conn.cursor()
    try:
        cursor.execute("DELETE FROM sys_users WHERE id = %s", (user_id,))
        conn.commit()
        return {"status": "success", "message": "用户删除成功"}
    except Exception as exc:
        conn.rollback()
        return {"status": "error", "message": str(exc)}
    finally:
        cursor.close()
        conn.close()
