/* product.c - Implementasi model Product */
#include "product.h"

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

/* Kode error yang dipakai product_create.
 * Nilai negatif agar mudah dibedakan dari id positif. */
#define PRODUCT_ERR_NAME   (-1)
#define PRODUCT_ERR_PRICE  (-2)
#define PRODUCT_ERR_STOCK  (-3)
#define PRODUCT_ERR_ID     (-4)

int product_is_valid(const Product *p) {
    if (p == NULL) {
        return 0;
    }
    if (p->id <= 0 || p->id > PRODUCT_ID_MAX) {
        return 0;
    }
    if (p->name[0] == '\0') {
        return 0;
    }
    if (p->price < 0.0 || isnan(p->price) || isinf(p->price)) {
        return 0;
    }
    if (p->stock < 0) {
        return 0;
    }
    return 1;
}

int product_create(Product *p, int id, const char *name,
                   double price, int stock) {
    if (p == NULL || name == NULL) {
        return PRODUCT_ERR_NAME;
    }
    if (id <= 0 || id > PRODUCT_ID_MAX) {
        return PRODUCT_ERR_ID;
    }
    if (price < 0.0 || isnan(price) || isinf(price)) {
        return PRODUCT_ERR_PRICE;
    }
    if (stock < 0) {
        return PRODUCT_ERR_STOCK;
    }

    p->id = id;
    /* Salin nama dengan aman: selalu tutup dengan terminator. */
    strncpy(p->name, name, PRODUCT_NAME_MAX - 1);
    p->name[PRODUCT_NAME_MAX - 1] = '\0';
    p->price = price;
    p->stock = stock;

    if (!product_is_valid(p)) {
        return PRODUCT_ERR_NAME;
    }
    return 0;
}

void product_print(const Product *p) {
    if (p == NULL) {
        printf("(null product)\n");
        return;
    }
    printf("[%06d] %-30s  Rp%10.2f  stok=%4d\n",
           p->id, p->name, p->price, p->stock);
}
