from __future__ import annotations

import logging
from typing import Any

logger = logging.getLogger(__name__)


class ErpUserMixin:
    def list_users(self) -> list[dict[str, Any]]:
        """Lấy danh sách toàn bộ người dùng và vai trò RBAC."""
        sql = """
            SELECT u.*, emp.job_title, emp.phone
            FROM erp_users u
            LEFT JOIN employees emp ON u.linked_employee_id = emp.id
            ORDER BY u.created_at DESC;
        """
        with self.get_connection() as conn, conn.cursor() as cur:
            cur.execute(sql)
            return cur.fetchall()

    def update_user_role(self, user_id: str, new_role: str) -> dict[str, Any]:
        """Cập nhật vai trò phân quyền cho tài khoản người dùng."""
        sql = """
            UPDATE erp_users
            SET role = %s, updated_at = NOW()
            WHERE id = %s
            RETURNING *;
        """
        with self.get_connection() as conn, conn.cursor() as cur:
            cur.execute(sql, (new_role, user_id))
            conn.commit()
            row = cur.fetchone()
            if not row:
                raise ValueError(f"Không tìm thấy người dùng với ID {user_id}")
            return row
