/* SPDX-License-Identifier: GPL-2.0-only */

#include <ppm/manifest.h>

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

#define CHECK(expr) do {                                            \
    if (!(expr)) {                                                  \
        fprintf(stderr, "FAIL: %s:%d: %s\n", __FILE__, __LINE__, #expr); \
        return 1;                                                   \
    }                                                               \
} while (0)

int main(void) {
    ppm_version_t v1 = {0}, v2 = {0};

    CHECK(ppm_version_parse("1.2.3", &v1) == PPM_OK);
    CHECK(v1.major == 1 && v1.minor == 2 && v1.patch == 3);
    CHECK(v1.pre == NULL && v1.build == NULL);

    CHECK(ppm_version_parse("1.2.4", &v2) == PPM_OK);
    CHECK(ppm_version_cmp(&v1, &v2) < 0);
    CHECK(ppm_version_cmp(&v2, &v1) > 0);
    CHECK(ppm_version_cmp(&v1, &v1) == 0);

    /* Prerelease < release of the same triple. */
    ppm_version_t rc = {0}, rel = {0};
    CHECK(ppm_version_parse("1.0.0-rc.1", &rc) == PPM_OK);
    CHECK(rc.pre && strcmp(rc.pre, "rc.1") == 0);
    CHECK(ppm_version_parse("1.0.0", &rel) == PPM_OK);
    CHECK(ppm_version_cmp(&rc, &rel) < 0);

    /* Build metadata round-trips but does not affect ordering. */
    ppm_version_t b1 = {0}, b2 = {0};
    CHECK(ppm_version_parse("1.0.0+a", &b1) == PPM_OK);
    CHECK(ppm_version_parse("1.0.0+b", &b2) == PPM_OK);
    CHECK(ppm_version_cmp(&b1, &b2) == 0);

    /* Malformed input rejected. */
    ppm_version_t bad = {0};
    CHECK(ppm_version_parse("not-a-version", &bad) == PPM_ERR_PARSE);
    CHECK(ppm_version_parse("1.0", &bad)            == PPM_ERR_PARSE);
    CHECK(ppm_version_parse("",   &bad)             == PPM_ERR_PARSE);

    ppm_version_dispose(&v1);
    ppm_version_dispose(&v2);
    ppm_version_dispose(&rc);
    ppm_version_dispose(&rel);
    ppm_version_dispose(&b1);
    ppm_version_dispose(&b2);
    ppm_version_dispose(&bad);

    printf("ok\n");
    return 0;
}
