#include "cgi.h"

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

void cgi_header(const char *content_type) {
    printf("Content-Type: %s; charset=UTF-8\r\n\r\n", content_type);
}

void cgi_status_header(const char *status, const char *content_type) {
    printf("Status: %s\r\n", status);
    printf("Content-Type: %s; charset=UTF-8\r\n\r\n", content_type);
}

void cgi_redirect(const char *location) {
    printf("Status: 302 Found\r\n");
    printf("Location: %s\r\n\r\n", location);
}

int cgi_read_post_body(char **out, size_t max_size) {
    const char *len_text = getenv("CONTENT_LENGTH");
    char *end = NULL;
    long len;

    *out = NULL;

    if (len_text == NULL || len_text[0] == '\0') {
        return 0;
    }

    len = strtol(len_text, &end, 10);
    if (end == len_text || *end != '\0' || len < 0 || (size_t)len > max_size) {
        return 0;
    }

    *out = malloc((size_t)len + 1);
    if (*out == NULL) {
        return 0;
    }

    size_t n = fread(*out, 1, (size_t)len, stdin);
    (*out)[n] = '\0';

    return n == (size_t)len;
}
