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

#define FILE_PATH "/srv/http/work_orders_debug.json"
#define TEMP_PATH "/srv/http/work_orders_debug_tmp.json"

int main(void) {
    char *len_str = getenv("CONTENT_LENGTH");
    int len = len_str ? atoi(len_str) : 0;
    char post[100] = {0};

    printf("Content-Type: text/plain\r\n\r\n");

    if (len <= 0 || len >= sizeof(post)) {
        printf("Ongeldige invoer");
        return 1;
    }

    fread(post, 1, len, stdin);
    post[len] = '\0';

    char *id_str = strstr(post, "id=");
    if (!id_str) {
        printf("Geen ID opgegeven");
        return 1;
    }
    id_str += 3;

    int delete_id = atoi(id_str);
    if (delete_id <= 0) {
        printf("Ongeldige ID");
        return 1;
    }

    FILE *in = fopen(FILE_PATH, "r");
    if (!in) {
        printf("Fout bij openen van JSON-bestand");
        return 1;
    }

    char json[32768];
    fread(json, 1, sizeof(json) - 1, in);
    fclose(in);
    json[sizeof(json) - 1] = '\0';

    // Rebuild JSON array
    FILE *out = fopen(TEMP_PATH, "w");
    if (!out) {
        printf("Fout bij schrijven van tijdelijk bestand");
        return 1;
    }

    fprintf(out, "[\n");

    char *p = json;
    int found = 0;
    int first = 1;

    while ((p = strchr(p, '{'))) {
        char *end = p;
        int depth = 0;
        while (*end) {
            if (*end == '{') depth++;
            else if (*end == '}') depth--;
            if (depth == 0) break;
            end++;
        }
        if (depth != 0 || !*end) break;

        char block[2048];
        int block_len = end - p + 1;
        if (block_len >= sizeof(block)) block_len = sizeof(block) - 1;
        strncpy(block, p, block_len);
        block[block_len] = '\0';

        // Extract ID from block
        char *id_field = strstr(block, "\"id\"");
        if (id_field) {
            int id_val;
            if (sscanf(id_field, "\"id\": %d", &id_val) == 1) {
                if (id_val == delete_id) {
                    // Soft delete: replace "deleted": false with "deleted": true
                    char *del_field = strstr(block, "\"deleted\": false");
                    if (del_field) {
                        strncpy(del_field, "\"deleted\": true ", strlen("\"deleted\": true "));
                        found = 1;
                    }
                }
            }
        }

        if (!first) fprintf(out, ",\n");
        fprintf(out, "  %s", block);
        first = 0;

        p = end + 1;
    }

    fprintf(out, "\n]\n");
    fclose(out);

    // Replace old file
    rename(TEMP_PATH, FILE_PATH);

    if (found)
        printf("OK");
    else
        printf("Niet gevonden");

    return 0;
}

