# Platform Credentials Management
# Manages credentials and tokens for platform services

# user/config star-import was dead — dropped (ADR-025 Phase 3 Layer 2).

# Get credentials namespace path for workspace
export def get-credentials-namespace [workspace_name: string] {
    [([$env.HOME ".provisioning" "credentials" $workspace_name] | path join)]
    | get 0
}

# Get credential from storage
export def get-credential [
    workspace_name: string
    category: string
    name: string
] {
    # First try environment variable
    let env_var_name = (
        $"($workspace_name)_($category)_($name)"
        | str upcase
        | str replace --all " " "_"
        | str replace --all "-" "_"
    )

    if $env_var_name in $env {
        return ($env | get $env_var_name)
    }

    # Then try keyring if available
    # (Simplified - actual implementation would use nu_plugin_auth)

    # Finally try vault file
    let vault_path = ([
        (get-credentials-namespace $workspace_name)
        $category
        $"($name).credential"
    ] | path join)

    if ($vault_path | path exists) {
        open $vault_path
    } else {
        error make {
            msg: $"Credential not found: ($category)/($name) for workspace ($workspace_name)"
        }
    }
}

# Store credential
export def store-credential [
    workspace_name: string
    category: string
    name: string
    value: string
] {
    # Store in environment variable (simplest approach)
    let env_var_name = (
        $"($workspace_name)_($category)_($name)"
        | str upcase
        | str replace --all " " "_"
        | str replace --all "-" "_"
    )

    load-env { ($env_var_name): $value }

    {
        storage: "env"
        key: $env_var_name
        success: true
    }
}

# Delete credential
export def delete-credential [
    workspace_name: string
    category: string
    name: string
] {
    # In a real implementation, this would:
    # - Remove from keyring
    # - Remove from vault file
    # - Remove from environment

    print $"Deleted credential: ($category)/($name) for workspace ($workspace_name)"
}

# List all credentials for workspace
export def list-workspace-credentials [workspace_name: string] {
    let namespace = (get-credentials-namespace $workspace_name)

    if not ($namespace | path exists) {
        return []
    }

    # In a real implementation, scan the vault directory structure
    []
}

# Check if credential exists
export def credential-exists [
    workspace_name: string
    category: string
    name: string
] {
    let env_var_name = (
        $"($workspace_name)_($category)_($name)"
        | str upcase
        | str replace --all " " "_"
        | str replace --all "-" "_"
    )

    ($env_var_name in $env)
}
