#include "cgi.h"
#include "form.h"
#include "html.h"
#include "session.h"

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

#define MAX_ITEMS 8
#define MAX_POST 2048

int main(void) {
    FormItem items[MAX_ITEMS];
    Session session;
    char *body = NULL;
    char sid[65];

    if (!cgi_read_post_body(&body, MAX_POST)) {
        cgi_status_header("400 Bad Request", "text/plain");
        printf("invalid post body\n");
        return 0;
    }

    int count = form_parse(body, items, MAX_ITEMS);
    const char *user_id = form_get(items, count, "user_id");
    const char *username = form_get(items, count, "username");

    session.user_id = user_id != NULL ? atoi(user_id) : 0;
    snprintf(session.username, sizeof(session.username), "%s", username != NULL ? username : "");

    if (session.user_id <= 0 || session.username[0] == '\0' ||
        !session_generate_id(sid, sizeof(sid)) ||
        !session_save(sid, &session)) {
        form_free(items, count);
        free(body);
        cgi_status_header("500 Internal Server Error", "text/plain");
        printf("failed to create development session\n");
        return 1;
    }

    session_set_cookie(sid);
    cgi_header("text/html");
    printf("<!DOCTYPE html><html lang=\"ja\"><body>\n");
    printf("<h1>Logged in for local development</h1>\n");
    printf("<p>User: ");
    html_escape_print(stdout, session.username);
    printf("</p>\n");
    printf("<p><a href=\"/cgi-bin/diary_form.cgi\">日記を書く</a></p>\n");
    printf("<p><a href=\"/cgi-bin/diary_list.cgi\">日記一覧</a></p>\n");
    printf("</body></html>\n");

    form_free(items, count);
    free(body);
    return 0;
}
