<?php
if (!defined('ABSPATH')) exit;

/** Key helpers */
function afb_status_key(string $request_id): string { return "afb_status_$request_id"; }
function afb_idem_key(string $request_id): string   { return "afb_req_$request_id"; }

/** Create/overwrite a status object */
function afb_status_init(string $request_id, array $seed = []) {
    $seed = array_merge([
        'request_id' => $request_id,
        'task_gid'   => null,
        'phase'      => 'create',         // create|upload|enrich|done|error
        'steps'      => [],               // [{k, ok, ms, msg}]
        'uploads'    => ['total'=>0,'done'=>0,'failed'=>[]],
        'errors'     => [],
        'updated_at' => current_time('mysql'),
    ], $seed);
    update_option(afb_status_key($request_id), $seed, false);
    return $seed;
}

/** Read current status (never null; will synthesize minimal shell) */
function afb_status_get(string $request_id): array {
    $opt = get_option(afb_status_key($request_id), null);
    if (is_array($opt)) return $opt;
    return ['request_id'=>$request_id,'phase'=>'unknown','steps'=>[],'uploads'=>['total'=>0,'done'=>0,'failed'=>[]],'errors'=>[],'updated_at'=>current_time('mysql')];
}

/** Merge + bump timestamp */
function afb_status_merge(string $request_id, array $patch): array {
    $cur = afb_status_get($request_id);
    $new = array_replace_recursive($cur, $patch);
    $new['updated_at'] = current_time('mysql');
    update_option(afb_status_key($request_id), $new, false);
    return $new;
}

/** Idempotency map: request_id → task_gid */
function afb_idem_remember(string $request_id, string $task_gid): void {
    update_option(afb_idem_key($request_id), $task_gid, false);
}
function afb_idem_lookup(string $request_id): ?string {
    $v = get_option(afb_idem_key($request_id), null);
    return $v ? (string)$v : null;
}

// ── Secret store (server-only; never exposed via status endpoint) ──
function afb_secret_key(string $request_id): string { return "afb_secret_$request_id"; }

/** Merge secret values for this request_id (e.g., PAT, canonical task_gid) */
function afb_secret_set(string $request_id, array $values): void {
    $k   = afb_secret_key($request_id);
    $cur = get_option($k, []);
    if (!is_array($cur)) $cur = [];
    $new = array_replace($cur, $values);
    update_option($k, $new, false);
}

/** Get secret values (returns [] if none). */
function afb_secret_get(string $request_id): array {
    $v = get_option(afb_secret_key($request_id), []);
    return is_array($v) ? $v : [];
}

