/* storage.c -- persistensi tugas ke file teks. */

#include "storage.h"

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

static void potong_newline(char *s) {
    size_t n = strlen(s);
    while (n > 0 && (s[n - 1] == '\n' || s[n - 1] == '\r')) {
        s[--n] = '\0';
    }
}

StorageStatus storage_simpan(const TaskList *list, const char *path) {
    if (list == 0 || path == 0) return STORAGE_ERR_BUKA_FILE;
    FILE *f = fopen(path, "w");
    if (f == 0) return STORAGE_ERR_BUKA_FILE;

    fprintf(f, "%d\n", list->jumlah);
    for (int i = 0; i < list->jumlah; i++) {
        const Task *t = &list->data[i];
        /* Ganti | di judul/deskripsi dengan spasi agar parsing tetap aman. */
        fprintf(f, "%d|%s|%s|%d|%d\n",
                t->id, t->judul, t->deskripsi, (int)t->status, (int)t->prioritas);
    }

    if (fclose(f) != 0) return STORAGE_ERR_TULIS;
    return STORAGE_OK;
}

StorageStatus storage_muat(TaskList *list, const char *path) {
    if (list == 0 || path == 0) return STORAGE_ERR_BUKA_FILE;
    FILE *f = fopen(path, "r");
    if (f == 0) return STORAGE_ERR_BUKA_FILE;

    int jumlah = 0;
    if (fscanf(f, "%d\n", &jumlah) != 1) {
        fclose(f);
        return STORAGE_ERR_FORMAT;
    }
    if (jumlah < 0 || jumlah > TASK_MAKS) {
        fclose(f);
        return STORAGE_ERR_FORMAT;
    }

    char baris[512];
    int id_terbesar = list->id_berikutnya - 1;

    for (int i = 0; i < jumlah; i++) {
        if (fgets(baris, sizeof(baris), f) == 0) {
            fclose(f);
            return STORAGE_ERR_FORMAT;
        }
        potong_newline(baris);

        int id, status, prioritas;
        char judul[TASK_JUDUL_MAKS];
        char deskripsi[TASK_DESKRIPSI_MAKS];

        int parsed = sscanf(baris, "%d|%79[^|]|%199[^|]|%d|%d",
                            &id, judul, deskripsi, &status, &prioritas);
        if (parsed < 5) {
            fclose(f);
            return STORAGE_ERR_FORMAT;
        }
        if (list->jumlah >= TASK_MAKS) break;

        Task *t = &list->data[list->jumlah];
        t->id = id;
        strncpy(t->judul, judul, TASK_JUDUL_MAKS - 1);
        t->judul[TASK_JUDUL_MAKS - 1] = '\0';
        strncpy(t->deskripsi, deskripsi, TASK_DESKRIPSI_MAKS - 1);
        t->deskripsi[TASK_DESKRIPSI_MAKS - 1] = '\0';
        t->status = (TaskStatus)status;
        t->prioritas = (TaskPrioritas)prioritas;
        list->jumlah++;

        if (id > id_terbesar) id_terbesar = id;
    }

    list->id_berikutnya = id_terbesar + 1;
    fclose(f);
    return STORAGE_OK;
}
