/*
 * util_amount.c - 금액/통화 유틸리티 (plain C, 공유)
 */
#include "acq_util.h"

#include <string.h>
#include <ctype.h>
#include <stdio.h>

#define AMOUNT_MAX  100000000L

long amount_parse(const char *field, int len)
{
    long v = 0;
    int  i;
    if (!field || len <= 0)
        return -1;
    for (i = 0; i < len; i++) {
        char c = field[i];
        if (c == ' ')
            continue;
        if (!isdigit((unsigned char)c))
            return -1;
        v = v * 10 + (c - '0');
    }
    return v;
}

int amount_format(long amount, char *out, int len)
{
    char tmp[32];
    int  n;
    if (!out || len <= 0 || amount < 0)
        return -1;
    n = snprintf(tmp, sizeof(tmp), "%0*ld", len, amount);
    if (n < 0 || n > len)
        return -1;
    memcpy(out, tmp, len);
    return 0;
}

void amount_format_won(long amount, char *out, int outlen)
{
    char raw[32];
    int  n, i, j, digits, first;
    if (!out || outlen <= 0)
        return;
    n = snprintf(raw, sizeof(raw), "%ld", amount);
    if (n < 0) { out[0] = '\0'; return; }
    first = (raw[0] == '-') ? 1 : 0;
    digits = n - first;
    j = 0;
    if (first && j < outlen - 1)
        out[j++] = '-';
    for (i = first; i < n && j < outlen - 1; i++) {
        int pos = i - first;
        if (pos > 0 && (digits - pos) % 3 == 0)
            if (j < outlen - 1)
                out[j++] = ',';
        out[j++] = raw[i];
    }
    out[j] = '\0';
}

int amount_is_valid(long amount)
{
    return (amount >= 1 && amount <= AMOUNT_MAX) ? 1 : 0;
}
