# (c) cavaliba.com  - data/api - keyname.py
#
# POST /api/keyname/
# ?s=SCHEMANAME                 (required, classname)
# &old=OLDKEYNAME                (required)
# &new=NEWKEYNAME                (required)
# &force=false                   (optional, default: false - allow rename on user/group/role)
# &dryrun=true                   (optional, default: true - safe by default)

"""
/api/keyname/: rename an instance's keyname (dry-run by default), delegating to
app_data.keyname.rename.

Method inventory: keyname.
"""

from django.views.decorators.csrf import csrf_exempt

import app_data.api.helper as helper
from app_data.api.aaa import start_api
from app_data.keyname import rename
from app_home.log import DEBUG, log


@csrf_exempt
def keyname(request):
    """POST-only: validate s/old/new/force/dryrun query params and rename an
    instance's keyname via app_data.keyname.rename; dryrun defaults to True."""

    aaa_api = start_api(request, permission="p_keyname_rename")
    if not aaa_api["is_allowed"]:
        return helper.send_denied()

    if request.method != "POST":
        return helper.send_error("method not allowed", 405)

    if aaa_api["is_readonly"]:
        return helper.send_denied("API key is read-only")

    schema_param = request.GET.get("s", "").strip()
    old_param = request.GET.get("old", "").strip()
    new_param = request.GET.get("new", "").strip()

    force_param = request.GET.get("force", "false").strip().lower()
    force = force_param in ("true", "1", "yes")

    # safe by default: unlike other write endpoints, an omitted dryrun means "don't write"
    dryrun_param = request.GET.get("dryrun", "true").strip().lower()
    dryrun = dryrun_param in ("true", "1", "yes")

    if not schema_param:
        return helper.send_error("missing required parameter: s", 400)
    if not old_param:
        return helper.send_error("missing required parameter: old", 400)
    if not new_param:
        return helper.send_error("missing required parameter: new", 400)

    result = rename(
        classname=schema_param,
        oldkeyname=old_param,
        newkeyname=new_param,
        dryrun=dryrun,
        force=force,
    )

    if result["errors"]:
        return helper.send_error("; ".join(result["errors"]), 400)

    log(
        DEBUG,
        aaa=aaa_api,
        app="api",
        view="keyname",
        action="POST",
        status="OK",
        data=f"schema={schema_param} old={old_param} new={new_param} dryrun={dryrun} force={force}",
    )

    return helper.send_response(request, result, 200)
