from flask import (
    Blueprint,
    request,
    jsonify,
    current_app,
    redirect,
)
from datetime import datetime, timedelta
from urllib.parse import urlencode

import base64
import hashlib
import hmac
import secrets
import requests
import jwt

from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import rsa

from flask_login import login_required, current_user

from extensions import db
from models import Employee, WorkspaceOAuthCode

integration_bp = Blueprint("integration", __name__, url_prefix="/integration")
oauth_bp = Blueprint("oauth", __name__, url_prefix="/oauth")
oidc_metadata_bp = Blueprint("oidc_metadata", __name__)

# ---------------------------------------------------------
# Workspace OAuth / OpenID Connect helpers
# ---------------------------------------------------------

OAUTH_ALLOWED_SCOPES = {
    "openid",
    "profile",
    "email",
}

def _read_key_file(config_name: str) -> bytes:
    """
    Read an OAuth signing key from the configured filesystem path.
    Keys must remain outside the public/static directory.
    """
    path = (
        current_app.config.get(config_name, "")
        or ""
    ).strip()

    if not path:
        raise RuntimeError(
            f"{config_name} is not configured."
        )

    try:
        with open(path, "rb") as key_file:
            return key_file.read()
    except OSError as exc:
        raise RuntimeError(
            f"Could not read OAuth key file configured by {config_name}: {exc}"
        ) from exc


def _oauth_private_key() -> bytes:
    return _read_key_file(
        "WORKSPACE_OAUTH_PRIVATE_KEY_PATH"
    )


def _oauth_public_key() -> bytes:
    return _read_key_file(
        "WORKSPACE_OAUTH_PUBLIC_KEY_PATH"
    )


def _base64url_uint(value: int) -> str:
    """
    Convert an RSA integer into an unpadded Base64URL string,
    as required by the JSON Web Key specification.
    """
    byte_length = max(
        1,
        (value.bit_length() + 7) // 8
    )

    raw = value.to_bytes(
        byte_length,
        byteorder="big"
    )

    return (
        base64.urlsafe_b64encode(raw)
        .rstrip(b"=")
        .decode("ascii")
    )


def _workspace_public_jwk() -> dict:
    public_key = serialization.load_pem_public_key(
        _oauth_public_key()
    )

    if not isinstance(public_key, rsa.RSAPublicKey):
        raise RuntimeError(
            "Configured OAuth public key is not an RSA public key."
        )

    numbers = public_key.public_numbers()

    return {
        "kty": "RSA",
        "use": "sig",
        "kid": current_app.config.get(
            "WORKSPACE_OAUTH_JWT_KEY_ID",
            "hrsoft-workspace-key-2026-01"
        ),
        "alg": current_app.config.get(
            "WORKSPACE_OAUTH_JWT_ALGORITHM",
            "RS256"
        ),
        "n": _base64url_uint(numbers.n),
        "e": _base64url_uint(numbers.e),
    }


def _oauth_json_response(payload: dict, status_code: int = 200):
    """
    OAuth token-related responses must not be cached.
    """
    response = jsonify(payload)
    response.status_code = status_code
    response.headers["Cache-Control"] = "no-store"
    response.headers["Pragma"] = "no-cache"
    return response


def _configured_oauth_client():
    return {
        "client_id": (
            current_app.config.get(
                "WORKSPACE_OAUTH_CLIENT_ID",
                ""
            )
            or ""
        ).strip(),

        "client_secret": (
            current_app.config.get(
                "WORKSPACE_OAUTH_CLIENT_SECRET",
                ""
            )
            or ""
        ).strip(),

        "redirect_uri": (
            current_app.config.get(
                "WORKSPACE_OAUTH_REDIRECT_URI",
                ""
            )
            or ""
        ).strip(),
    }


def _oauth_error_redirect(
    redirect_uri: str,
    error: str,
    description: str,
    state: str = None,
):
    params = {
        "error": error,
        "error_description": description,
    }

    if state:
        params["state"] = state

    separator = "&" if "?" in redirect_uri else "?"

    return redirect(
        f"{redirect_uri}{separator}{urlencode(params)}"
    )


def _hash_oauth_code(raw_code: str) -> str:
    return hashlib.sha256(
        raw_code.encode("utf-8")
    ).hexdigest()


def _validate_oauth_client_secret(
    supplied_client_id: str,
    supplied_client_secret: str,
) -> bool:
    configured = _configured_oauth_client()

    expected_id = configured["client_id"]
    expected_secret = configured["client_secret"]

    if not expected_id or not expected_secret:
        current_app.logger.error(
            "Workspace OAuth client credentials are not configured."
        )
        return False

    return (
        bool(supplied_client_id)
        and bool(supplied_client_secret)
        and hmac.compare_digest(
            supplied_client_id,
            expected_id
        )
        and hmac.compare_digest(
            supplied_client_secret,
            expected_secret
        )
    )


def _employee_oauth_claims(emp: Employee) -> dict:
    return {
        "sub": str(emp.id),
        "employee_code": emp.employee_code,
        "name": emp.full_name,
        "email": emp.email,
        "email_verified": bool(emp.email),
        "phone_number": emp.phone,

        "department": (
            emp.department.name
            if getattr(emp, "department", None)
            else None
        ),

        "designation": (
            emp.designation.title
            if getattr(emp, "designation", None)
            else None
        ),

        "role": (
            emp.role.name
            if getattr(emp, "role", None)
            else None
        ),

        "location": emp.location,
        "status": emp.status,
    }


def _issue_oauth_token(
    emp: Employee,
    *,
    client_id: str,
    scope: str,
    nonce: str = None,
    token_use: str = "access",
) -> str:
    now = datetime.utcnow()

    ttl_seconds = int(
        current_app.config.get(
            "WORKSPACE_OAUTH_TOKEN_TTL_SECONDS",
            3600
        )
    )

    issuer = (
        current_app.config.get(
            "WORKSPACE_OAUTH_ISSUER",
            ""
        )
        or ""
    ).rstrip("/")

    algorithm = (
        current_app.config.get(
            "WORKSPACE_OAUTH_JWT_ALGORITHM",
            "RS256"
        )
        or "RS256"
    ).strip()

    key_id = (
        current_app.config.get(
            "WORKSPACE_OAUTH_JWT_KEY_ID",
            ""
        )
        or ""
    ).strip()

    if not issuer:
        raise RuntimeError(
            "WORKSPACE_OAUTH_ISSUER is not configured."
        )

    if algorithm != "RS256":
        raise RuntimeError(
            "Workspace OAuth must use RS256."
        )

    if not key_id:
        raise RuntimeError(
            "WORKSPACE_OAUTH_JWT_KEY_ID is not configured."
        )

    payload = {
        "iss": issuer,
        "sub": str(emp.id),
        "aud": client_id,
        "iat": now,
        "nbf": now,
        "exp": now + timedelta(seconds=ttl_seconds),
        "jti": secrets.token_urlsafe(24),
        "scope": scope,
        "token_use": token_use,
    }

    if token_use == "id":
        payload.update(
            _employee_oauth_claims(emp)
        )

        if nonce:
            payload["nonce"] = nonce

    return jwt.encode(
        payload,
        _oauth_private_key(),
        algorithm=algorithm,
        headers={
            "kid": key_id,
            "typ": "JWT",
        },
    )

# -----------------------------
# Payload builder
# -----------------------------

def _is_hr_admin_user() -> bool:
    role_name = (
        getattr(getattr(current_user, "role", None), "name", "")
        or ""
    ).strip().lower()

    return role_name in (
        "admin",
        "hr",
        "hr admin",
        "demo admin",
    )

def employee_payload(emp: Employee, authenticated=True):
    reporting_manager = getattr(
        emp,
        "reporting_manager",
        None,
    )

    return {
        "unique_user_id": str(emp.id),
        "employee_code": emp.employee_code,
        "employee_name": emp.full_name,
        "email": emp.email,
        "authenticated": bool(authenticated),
        "mobile": emp.phone,
        "status": emp.status,
        "doj": (
            emp.date_of_joining.isoformat()
            if emp.date_of_joining
            else None
        ),
        "role": (
            emp.role.name
            if getattr(emp, "role", None)
            else None
        ),
        "department": (
            emp.department.name
            if getattr(emp, "department", None)
            else None
        ),
        "designation": (
            emp.designation.title
            if getattr(emp, "designation", None)
            else None
        ),
        "location": emp.location,
        "institute": getattr(emp, "institute", None),
        "reporting_manager": (
            reporting_manager.employee_code
            if reporting_manager
            else None
        ),
    }

# -----------------------------
# Webhook sender
# -----------------------------

def _linkers_headers():
    """
    Authentication headers required by Linkers Workspace.

    The API accepts Bearer authentication. X-HRMS-API-Key is included
    as an additional compatible authentication header.
    """
    token = (
        current_app.config.get("LINKERS_HRMS_API_TOKEN", "")
        or ""
    ).strip()

    if not token:
        raise RuntimeError("LINKERS_HRMS_API_TOKEN is not configured.")

    return {
        "Authorization": f"Bearer {token}",
        "Your-API-Key": token,
        "X-HRMS-API-Key": token,
        "Content-Type": "application/json",
        "Accept": "application/json",
    }

def _is_valid_linkers_request() -> bool:
    configured_token = (
        current_app.config.get("LINKERS_HRMS_API_TOKEN", "")
        or ""
    ).strip()

    if not configured_token:
        return False

    auth_header = (
        request.headers.get("Authorization", "")
        or ""
    ).strip()

    api_key_header = (
        request.headers.get("Your-API-Key")
        or request.headers.get("X-HRMS-API-Key")
        or ""
    ).strip()

    bearer_token = ""
    if auth_header.lower().startswith("bearer "):
        bearer_token = auth_header[7:].strip()

    bearer_valid = bool(bearer_token) and hmac.compare_digest(
        bearer_token,
        configured_token,
    )

    api_key_valid = bool(api_key_header) and hmac.compare_digest(
        api_key_header,
        configured_token,
    )

    return bearer_valid or api_key_valid

def send_employee_webhook(
    event_name: str,
    emp: Employee,
    old_data=None,
) -> bool:
    """
    Send an employee event to Linkers Workspace.

    Supported events:
      employee.created
      employee.updated
      employee.transferred
      employee.resigned
      employee.deleted
      department.changed
      designation.changed
    """

    allowed_events = {
        "employee.created",
        "employee.updated",
        "employee.transferred",
        "employee.resigned",
        "employee.deleted",
        "department.changed",
        "designation.changed",
    }

    if event_name not in allowed_events:
        current_app.logger.warning(
            "Unsupported Linkers employee webhook event: %s",
            event_name,
        )
        return False

    url = current_app.config.get(
        "LINKERS_HRMS_EMPLOYEE_WEBHOOK_URL"
    )

    if not url:
        current_app.logger.error(
            "LINKERS_HRMS_EMPLOYEE_WEBHOOK_URL is not configured."
        )
        return False

    payload = {
        "event_type": event_name,
        "employee": employee_payload(emp),
    }

    # Do not send old_data unless the client confirms that the API accepts it.
    # Their published sample contains event_type + employee only.

    try:
        response = requests.post(
            url,
            json=payload,
            headers=_linkers_headers(),
            timeout=current_app.config.get(
                "LINKERS_HRMS_TIMEOUT",
                15,
            ),
        )

        response_text = (response.text or "")[:2000]

        if response.ok:
            current_app.logger.info(
                "Linkers employee webhook succeeded. "
                "event=%s employee_id=%s status=%s response=%s",
                event_name,
                emp.id,
                response.status_code,
                response_text,
            )
            return True

        current_app.logger.error(
            "Linkers employee webhook rejected. "
            "event=%s employee_id=%s status=%s response=%s",
            event_name,
            emp.id,
            response.status_code,
            response_text,
        )
        return False

    except Exception:
        current_app.logger.exception(
            "Linkers employee webhook request failed. "
            "event=%s employee_id=%s",
            event_name,
            emp.id,
        )
        return False

def send_login_result(
    *,
    username: str,
    success: bool,
    employee: Employee = None,
    message: str = None,
) -> bool:
    """
    Notify Linkers Workspace about an HRMS authentication result.

    This function should never block HRMS login if Workspace is unavailable.
    """

    url = current_app.config.get(
        "LINKERS_HRMS_LOGIN_RESULT_URL"
    )

    if not url:
        current_app.logger.error(
            "LINKERS_HRMS_LOGIN_RESULT_URL is not configured."
        )
        return False

    payload = {
        "username": username,
        "success": bool(success),
        "authenticated": bool(success),
        "message": message or (
            "Authenticated successfully."
            if success
            else "Authentication failed."
        ),
        "timestamp": datetime.utcnow().isoformat() + "Z",
        "employee": (
            employee_payload(
                employee,
                authenticated=success,
            )
            if employee
            else None
        ),
    }

    try:
        response = requests.post(
            url,
            json=payload,
            headers=_linkers_headers(),
            timeout=current_app.config.get(
                "LINKERS_HRMS_TIMEOUT",
                15,
            ),
        )

        response_text = (response.text or "")[:2000]

        if response.ok:
            current_app.logger.info(
                "Linkers login result sent. "
                "username=%s success=%s status=%s",
                username,
                success,
                response.status_code,
            )
            return True

        current_app.logger.error(
            "Linkers login result rejected. "
            "username=%s success=%s status=%s response=%s",
            username,
            success,
            response.status_code,
            response_text,
        )
        return False

    except Exception:
        current_app.logger.exception(
            "Linkers login result request failed. "
            "username=%s success=%s",
            username,
            success,
        )
        return False
# -----------------------------
# Login verification service
# -----------------------------

@integration_bp.route("/auth/verify", methods=["POST"])
def verify_hrms_login():

    if not _is_valid_linkers_request():
        return jsonify({
            "success": False,
            "message": "Unauthorized request.",
        }), 401

    data = request.get_json(silent=True) or {}

    username = (data.get("username") or "").strip()
    password = data.get("password") or ""

    if not username or not password:
        return jsonify({
            "success": False,
            "message": "Username and password are required.",
        }), 400

    emp = (
        Employee.query
        .filter(
            db.or_(
                db.func.lower(Employee.email) == username.lower(),
                Employee.employee_code == username,
            )
        )
        .first()
    )

    if not emp:
        send_login_result(
            username=username,
            success=False,
            employee=None,
            message="Invalid credentials.",
        )

        return jsonify({
            "success": False,
            "message": "Invalid credentials.",
        }), 401

    status = (emp.status or "").strip().lower()

    if status not in (
        "active",
        "notice_period",
        "notice period",
    ):
        send_login_result(
            username=username,
            success=False,
            employee=emp,
            message="Employee is not active.",
        )

        return jsonify({
            "success": False,
            "message": "Employee is not active.",
            "employee": employee_payload(
                emp,
                authenticated=False,
            ),
        }), 403

    try:
        password_valid = emp.check_password(password)
    except Exception:
        current_app.logger.exception(
            "Employee password verification failed."
        )
        password_valid = False

    if not password_valid:
        send_login_result(
            username=username,
            success=False,
            employee=emp,
            message="Invalid credentials.",
        )

        return jsonify({
            "success": False,
            "message": "Invalid credentials.",
        }), 401

    send_login_result(
        username=username,
        success=True,
        employee=emp,
        message="Authenticated successfully.",
    )

    return jsonify({
        "success": True,
        "message": "Authenticated successfully.",
        "employee": employee_payload(
            emp,
            authenticated=True,
        ),
    }), 200

@integration_bp.route("/linkers/health", methods=["GET"])
@login_required
def linkers_health():
    if not _is_hr_admin_user():
        return jsonify({
            "success": False,
            "message": "Access denied.",
        }), 403

    url = current_app.config.get("LINKERS_HRMS_HEALTH_URL")
    if not url:
        return jsonify({
            "success": False,
            "message": "LINKERS_HRMS_HEALTH_URL is not configured.",
        }), 503

    try:
        response = requests.get(
            url,
            timeout=current_app.config.get(
                "LINKERS_HRMS_TIMEOUT",
                15,
            ),
        )

        try:
            response_data = response.json()
        except ValueError:
            response_data = {
                "raw_response": response.text[:2000]
            }

        return jsonify({
            "success": response.ok,
            "status_code": response.status_code,
            "workspace_response": response_data,
        }), 200 if response.ok else 502

    except requests.RequestException as exc:
        current_app.logger.exception(
            "Linkers health check failed."
        )

        return jsonify({
            "success": False,
            "message": str(exc),
        }), 502
    
# ---------------------------------------------------------
# Workspace OAuth authorization endpoint
# ---------------------------------------------------------

@oauth_bp.route("/authorize", methods=["GET"])
@login_required
def oauth_authorize():
    client_id = (
        request.args.get("client_id")
        or ""
    ).strip()

    redirect_uri = (
        request.args.get("redirect_uri")
        or ""
    ).strip()

    response_type = (
        request.args.get("response_type")
        or ""
    ).strip()

    scope_raw = (
        request.args.get("scope")
        or ""
    ).strip()

    state = (
        request.args.get("state")
        or ""
    ).strip()

    nonce = (
        request.args.get("nonce")
        or ""
    ).strip()

    configured = _configured_oauth_client()

    if not configured["client_id"]:
        return jsonify({
            "error": "server_error",
            "error_description": (
                "Workspace OAuth client is not configured."
            ),
        }), 503

    if (
        not client_id
        or not hmac.compare_digest(
            client_id,
            configured["client_id"]
        )
    ):
        return jsonify({
            "error": "unauthorized_client",
            "error_description": "Invalid client_id.",
        }), 401

    # Never redirect to an unregistered URL.
    if (
        not redirect_uri
        or redirect_uri != configured["redirect_uri"]
    ):
        return jsonify({
            "error": "invalid_request",
            "error_description": "Invalid redirect_uri.",
        }), 400

    if response_type != "code":
        return _oauth_error_redirect(
            redirect_uri,
            "unsupported_response_type",
            "Only response_type=code is supported.",
            state
        )

    if not state:
        return _oauth_error_redirect(
            redirect_uri,
            "invalid_request",
            "state is required.",
            state
        )

    requested_scopes = {
        scope.strip()
        for scope in scope_raw.split()
        if scope.strip()
    }

    if "openid" not in requested_scopes:
        return _oauth_error_redirect(
            redirect_uri,
            "invalid_scope",
            "The openid scope is required.",
            state
        )

    if not requested_scopes.issubset(
        OAUTH_ALLOWED_SCOPES
    ):
        return _oauth_error_redirect(
            redirect_uri,
            "invalid_scope",
            "One or more scopes are unsupported.",
            state
        )

    if not nonce:
        return _oauth_error_redirect(
            redirect_uri,
            "invalid_request",
            "nonce is required.",
            state
        )

    employee_status = (
        getattr(current_user, "status", "")
        or ""
    ).strip().lower()

    if employee_status not in (
        "active",
        "notice_period",
        "notice period",
    ):
        return _oauth_error_redirect(
            redirect_uri,
            "access_denied",
            "Employee account is not active.",
            state
        )

    raw_code = secrets.token_urlsafe(48)

    ttl_seconds = int(
        current_app.config.get(
            "WORKSPACE_OAUTH_CODE_TTL_SECONDS",
            300
        )
    )

    code_record = WorkspaceOAuthCode(
        code_hash=_hash_oauth_code(raw_code),
        employee_id=current_user.id,
        client_id=client_id,
        redirect_uri=redirect_uri,
        scope=" ".join(sorted(requested_scopes)),
        nonce=nonce,
        expires_at=(
            datetime.utcnow()
            + timedelta(seconds=ttl_seconds)
        ),
    )

    try:
        db.session.add(code_record)
        db.session.commit()

    except Exception:
        db.session.rollback()

        current_app.logger.exception(
            "Workspace OAuth authorization code creation failed."
        )

        return _oauth_error_redirect(
            redirect_uri,
            "server_error",
            "Could not create authorization code.",
            state
        )

    callback_params = {
        "code": raw_code,
        "state": state,
    }

    separator = "&" if "?" in redirect_uri else "?"

    return redirect(
        f"{redirect_uri}{separator}"
        f"{urlencode(callback_params)}"
    )

# ---------------------------------------------------------
# Workspace OAuth token endpoint
# ---------------------------------------------------------

@oauth_bp.route("/token", methods=["POST"])
def oauth_token():
    auth = request.authorization

    client_id = (
        auth.username
        if auth and auth.username
        else request.form.get("client_id")
    )

    client_secret = (
        auth.password
        if auth and auth.password
        else request.form.get("client_secret")
    )

    client_id = (client_id or "").strip()
    client_secret = client_secret or ""

    grant_type = (
        request.form.get("grant_type")
        or ""
    ).strip()

    raw_code = (
        request.form.get("code")
        or ""
    ).strip()

    redirect_uri = (
        request.form.get("redirect_uri")
        or ""
    ).strip()

    if not _validate_oauth_client_secret(
        client_id,
        client_secret
    ):
        return jsonify({
            "error": "invalid_client",
            "error_description": (
                "Client authentication failed."
            ),
        }), 401

    if grant_type != "authorization_code":
        return jsonify({
            "error": "unsupported_grant_type",
            "error_description": (
                "Only authorization_code is supported."
            ),
        }), 400

    if not raw_code or not redirect_uri:
        return jsonify({
            "error": "invalid_request",
            "error_description": (
                "code and redirect_uri are required."
            ),
        }), 400

    code_record = (
        WorkspaceOAuthCode.query
        .filter_by(
            code_hash=_hash_oauth_code(raw_code),
            client_id=client_id
        )
        .with_for_update()
        .first()
    )

    if not code_record:
        return jsonify({
            "error": "invalid_grant",
            "error_description": (
                "Authorization code is invalid."
            ),
        }), 400

    if code_record.is_used:
        return jsonify({
            "error": "invalid_grant",
            "error_description": (
                "Authorization code has already been used."
            ),
        }), 400

    if code_record.is_expired:
        return jsonify({
            "error": "invalid_grant",
            "error_description": (
                "Authorization code has expired."
            ),
        }), 400

    if not hmac.compare_digest(
        code_record.redirect_uri,
        redirect_uri
    ):
        return jsonify({
            "error": "invalid_grant",
            "error_description": (
                "redirect_uri does not match."
            ),
        }), 400

    emp = Employee.query.get(
        code_record.employee_id
    )

    if not emp:
        return jsonify({
            "error": "invalid_grant",
            "error_description": (
                "Employee account was not found."
            ),
        }), 400

    employee_status = (
        emp.status or ""
    ).strip().lower()

    if employee_status not in (
        "active",
        "notice_period",
        "notice period",
    ):
        return jsonify({
            "error": "access_denied",
            "error_description": (
                "Employee account is not active."
            ),
        }), 403

    try:
        access_token = _issue_oauth_token(
            emp,
            client_id=client_id,
            scope=code_record.scope,
            token_use="access"
        )

        id_token = _issue_oauth_token(
            emp,
            client_id=client_id,
            scope=code_record.scope,
            nonce=code_record.nonce,
            token_use="id"
        )

        code_record.used_at = datetime.utcnow()
        db.session.commit()

    except Exception:
        db.session.rollback()

        current_app.logger.exception(
            "Workspace OAuth token generation failed."
        )

        return jsonify({
            "error": "server_error",
            "error_description": (
                "Could not issue OAuth tokens."
            ),
        }), 500

    return _oauth_json_response({
        "access_token": access_token,
        "token_type": "Bearer",
        "expires_in": int(
            current_app.config.get(
                "WORKSPACE_OAUTH_TOKEN_TTL_SECONDS",
                3600
            )
        ),
        "scope": code_record.scope,
        "id_token": id_token,
    })

# ---------------------------------------------------------
# Workspace OpenID Connect user-info endpoint
# ---------------------------------------------------------

@oauth_bp.route("/userinfo", methods=["GET"])
def oauth_userinfo():
    authorization = (
        request.headers.get("Authorization")
        or ""
    ).strip()

    if not authorization.lower().startswith("bearer "):
        return jsonify({
            "error": "invalid_token",
            "error_description": (
                "Bearer access token is required."
            ),
        }), 401

    access_token = authorization[7:].strip()


    client_id = (
        current_app.config.get(
            "WORKSPACE_OAUTH_CLIENT_ID",
            ""
        )
        or ""
    ).strip()

    issuer = (
        current_app.config.get(
            "WORKSPACE_OAUTH_ISSUER",
            ""
        )
        or ""
    ).rstrip("/")

    try:
        claims = jwt.decode(
            access_token,
            _oauth_public_key(),
            algorithms=["RS256"],
            audience=client_id,
            issuer=issuer,
            options={
                "require": [
                    "iss",
                    "sub",
                    "aud",
                    "iat",
                    "exp",
                ]
            },
        )

    except jwt.ExpiredSignatureError:
        return jsonify({
            "error": "invalid_token",
            "error_description": "Token has expired.",
        }), 401

    except jwt.InvalidTokenError:
        return jsonify({
            "error": "invalid_token",
            "error_description": "Token is invalid.",
        }), 401

    if claims.get("token_use") != "access":
        return jsonify({
            "error": "invalid_token",
            "error_description": (
                "The supplied token is not an access token."
            ),
        }), 401

    try:
        employee_id = int(claims["sub"])

    except (KeyError, TypeError, ValueError):
        return jsonify({
            "error": "invalid_token",
            "error_description": (
                "Token subject is invalid."
            ),
        }), 401

    emp = Employee.query.get(employee_id)

    if not emp:
        return jsonify({
            "error": "invalid_token",
            "error_description": (
                "Employee account was not found."
            ),
        }), 401

    employee_status = (
        emp.status or ""
    ).strip().lower()

    if employee_status not in (
        "active",
        "notice_period",
        "notice period",
    ):
        return jsonify({
            "error": "invalid_token",
            "error_description": (
                "Employee account is inactive."
            ),
        }), 401

    return jsonify(
        _employee_oauth_claims(emp)
    ), 200

# ---------------------------------------------------------
# Workspace OpenID Connect JWKS endpoint
# ---------------------------------------------------------

@oauth_bp.route("/jwks.json", methods=["GET"])
def oauth_jwks():
    try:
        response = jsonify({
            "keys": [
                _workspace_public_jwk()
            ]
        })

        # Public signing keys may be cached briefly.
        response.headers["Cache-Control"] = (
            "public, max-age=300"
        )

        return response, 200

    except Exception:
        current_app.logger.exception(
            "Workspace JWKS generation failed."
        )

        return jsonify({
            "error": "server_error",
            "error_description": (
                "Could not load the OpenID signing key."
            ),
        }), 500
    
# ---------------------------------------------------------
# Workspace OpenID Connect discovery metadata
# ---------------------------------------------------------

@oauth_bp.route(
    "/.well-known/openid-configuration",
    methods=["GET"]
)
def oauth_openid_configuration():
    issuer = (
        current_app.config.get(
            "WORKSPACE_OAUTH_ISSUER",
            ""
        )
        or ""
    ).rstrip("/")

    if not issuer:
        return jsonify({
            "error": "server_error",
            "error_description": (
                "OAuth issuer is not configured."
            ),
        }), 503

    return jsonify({
        "issuer": issuer,
        "authorization_endpoint": (
            f"{issuer}/oauth/authorize"
        ),
        "token_endpoint": (
            f"{issuer}/oauth/token"
        ),
        "userinfo_endpoint": (
            f"{issuer}/oauth/userinfo"
        ),
        "jwks_uri": (
            f"{issuer}/oauth/jwks.json"
        ),
        "response_types_supported": [
            "code"
        ],
        "grant_types_supported": [
            "authorization_code"
        ],
        "subject_types_supported": [
            "public"
        ],
        "id_token_signing_alg_values_supported": [
            "RS256"
        ],
        "token_endpoint_auth_methods_supported": [
            "client_secret_basic",
            "client_secret_post"
        ],
        "scopes_supported": [
            "openid",
            "profile",
            "email"
        ],
        "claims_supported": [
            "iss",
            "sub",
            "aud",
            "exp",
            "iat",
            "nonce",
            "name",
            "email",
            "email_verified",
            "phone_number",
            "employee_code",
            "department",
            "designation",
            "role",
            "location",
            "status"
        ],
    }), 200

@oidc_metadata_bp.route(
    "/.well-known/openid-configuration",
    methods=["GET"]
)
def openid_configuration():
    issuer = (
        current_app.config.get(
            "WORKSPACE_OAUTH_ISSUER",
            ""
        )
        or ""
    ).rstrip("/")

    if not issuer:
        return jsonify({
            "error": "server_error",
            "error_description": (
                "OAuth issuer is not configured."
            ),
        }), 503

    return jsonify({
        "issuer": issuer,
        "authorization_endpoint": (
            f"{issuer}/oauth/authorize"
        ),
        "token_endpoint": (
            f"{issuer}/oauth/token"
        ),
        "userinfo_endpoint": (
            f"{issuer}/oauth/userinfo"
        ),
        "jwks_uri": (
            f"{issuer}/oauth/jwks.json"
        ),
        "response_types_supported": [
            "code"
        ],
        "grant_types_supported": [
            "authorization_code"
        ],
        "subject_types_supported": [
            "public"
        ],
        "id_token_signing_alg_values_supported": [
            "RS256"
        ],
        "token_endpoint_auth_methods_supported": [
            "client_secret_basic",
            "client_secret_post"
        ],
        "scopes_supported": [
            "openid",
            "profile",
            "email"
        ],
        "claims_supported": [
            "iss",
            "sub",
            "aud",
            "exp",
            "iat",
            "nonce",
            "name",
            "email",
            "email_verified",
            "phone_number",
            "employee_code",
            "department",
            "designation",
            "role",
            "location",
            "status"
        ],
    }), 200