
#include "Webserv.hpp"


void	Webserv::_post(Client *client)
{
/*
	WIP
	https://www.rfc-editor.org/rfc/rfc9110.html#name-post
*/
	std::string		path = client->get_rq_abs_path();
	path.insert(0, client->assigned_location->root);

	/* CGI Here ? */

	_post_file(client, path);
}

void	Webserv::_post_file(Client *client, const std::string &path)
{
	std::ofstream	ofd;

	bool	file_existed;
	if (access(path.c_str(), F_OK) == -1)
		file_existed = false;
	else
		file_existed = true;

	// How to determine status 403 for file that dont already exist ?
	if (file_existed && access(path.c_str(), W_OK) == -1)
	{
		std::perror("err access()");
		client->status = 403;
		return ;
	}

	ofd.open(path.c_str(), std::ios::trunc);
	if (!ofd)
	{
		std::cerr << path << ": ofd.open fail" << '\n';
		client->status = 500;
	}
	else
	{
		// Content-Length useless at this point ?
		ofd << client->get_rq_body();
		if (!ofd)
		{
			std::cerr << path << ": ofd.write fail" << '\n';
			client->status = 500;
		}
		else if (file_existed)
		{
			client->status = 200;
			// WIP https://www.rfc-editor.org/rfc/rfc9110.html#name-200-ok
		}
		else
		{
			client->status = 201;
			// WIP https://www.rfc-editor.org/rfc/rfc9110.html#section-9.3.3-4
		}
	}
}
