#!/bin/bash

# Source of truth for the Locations editor form layout: which CFG_BACKUP_LOC_*
# fields apply to each backup location type, in render order. Emitted as
# data/backup/generated/schema.json so the frontend builds the form from data
# instead of a hardcoded map (it keeps a fallback only). ENGINE stays in the
# list — the frontend folds it into the Advanced tab via the per-field
# "advanced" flag from configs.json; this file is purely about applicability
# and order.

webuiGenerateBackupSchema()
{
    local out_dir="$containers_dir/libreportal/frontend/data/backup/generated"
    local out_file="$out_dir/schema.json"
    runFileOp mkdir -p "$out_dir"

    # "<type>|FIELD,FIELD,..." — order here is the form's render order.
    local rows=(
        "local|TYPE,NAME,ENGINE,PATH_MODE,PATH,APPEND_ONLY"
        "sftp|TYPE,NAME,ENGINE,SSH_USER,SSH_HOST,SSH_PORT,SSH_PATH,SSH_AUTH,SSH_PASS,URI,APPEND_ONLY"
        "rest|TYPE,NAME,ENGINE,URI,APPEND_ONLY"
        "s3|TYPE,NAME,ENGINE,URI,S3_ACCESS_KEY,S3_SECRET_KEY,APPEND_ONLY"
        "b2|TYPE,NAME,ENGINE,URI,B2_ACCOUNT_ID,B2_ACCOUNT_KEY,APPEND_ONLY"
        "gs|TYPE,NAME,ENGINE,URI,APPEND_ONLY"
        "azure|TYPE,NAME,ENGINE,URI,APPEND_ONLY"
        "rclone|TYPE,NAME,ENGINE,URI,APPEND_ONLY"
    )

    local json="{\"generated_at\":\"$(date -Iseconds)\",\"types\":{"
    local first=true row type fields f farr firstf
    for row in "${rows[@]}"; do
        type="${row%%|*}"
        fields="${row#*|}"
        $first || json+=","
        first=false
        json+="\"$type\":["
        firstf=true
        IFS=',' read -ra farr <<< "$fields"
        for f in "${farr[@]}"; do
            $firstf || json+=","
            firstf=false
            json+="\"$f\""
        done
        json+="]"
    done
    json+="}}"

    echo "$json" | runFileWrite "$out_file"
    isSuccessful "Backup location schema regenerated"
}
