/**
 * src/lib/ae_core/core__idb_sort.ts
 *
 * Shared utility for computing tmp_sort_* fields stored in Dexie.
 * All fields are designed for ascending .sortBy() — no .reverse() needed.
 *
 * Encoding rules:
 *   priority — inverted boolean: true→'0', false→'1' so priority=true sorts first (ASC)
 *   sort     — zero-padded integer string so "00000010" < "00000020" (correct numeric order)
 *   all other fields — appended as-is; ISO 8601 datetimes already sort correctly
 *
 * Usage:
 *   const { tmp_sort_1, tmp_sort_2, tmp_sort_3 } = build_tmp_sort({
 *       prefix: [obj.group ?? '0'],      // fields before priority (optional)
 *       priority: obj.priority,
 *       sort: obj.sort,
 *       fields_1: [obj.start_datetime],  // appended to base for tmp_sort_1
 *       fields_2: [obj.name],            // appended after fields_1 for tmp_sort_2
 *       fields_3: [obj.updated_on],      // appended after fields_2 for tmp_sort_3
 *   });
 */
export function build_tmp_sort({
    prefix = [],
    priority,
    sort,
    fields_1 = [],
    fields_2 = [],
    fields_3 = [],
    pad_width = 8
}: {
    prefix?: (string | null | undefined)[];
    priority?: boolean | null;
    sort?: number | string | null;
    fields_1?: (string | null | undefined)[];
    fields_2?: (string | null | undefined)[];
    fields_3?: (string | null | undefined)[];
    pad_width?: number;
}): { tmp_sort_1: string; tmp_sort_2: string; tmp_sort_3: string } {
    const clean = (v: string | null | undefined): string => v ?? '';

    const p = priority ? '0' : '1';
    const s = String(Number(sort ?? 0)).padStart(pad_width, '0');

    const parts_base = [...prefix.map(clean), p, s].join('_');
    const parts_1 = fields_1.map(clean).filter(Boolean).join('_');
    const parts_2 = fields_2.map(clean).filter(Boolean).join('_');
    const parts_3 = fields_3.map(clean).filter(Boolean).join('_');

    const tmp_sort_1 = [parts_base, parts_1].filter(Boolean).join('_');
    const tmp_sort_2 = [tmp_sort_1, parts_2].filter(Boolean).join('_');
    const tmp_sort_3 = [tmp_sort_2, parts_3].filter(Boolean).join('_');

    return { tmp_sort_1, tmp_sort_2, tmp_sort_3 };
}
