import { addLog } from "./log";

export const getPelaporan = async (query = {}) => {
	try {
		let url = "http://localhost:5000/pelaporan";
		if (query.ptId && query.number) {
			url += `?number=${query.number}&ptId=${query.ptId}`;
		} else if (query.penjadwalan) {
			url += "?penjadwalan=true";
		} else if (query.pemeriksaan) {
			url += "?pemeriksaan=true";
		}
		const res = await fetch(url);
		return await res.json();
	} catch (error) {
		console.log("error", error);
		return false;
	}
};

export const createPelaporan = async (data) => {
	try {
		const res = await fetch("http://localhost:5000/pelaporan/create", {
			method: "POST",
			body: data,
		});
		const result = await res.json();
		addLog({ status: "SUCCESS", action: "CREATE", from: { id: result.created._id, data: "pelaporan" }, description: "membuat laporan" });
		return result;
	} catch (error) {
		console.log("error", error);
		addLog({ status: "FAIL", action: "CREATE", from: { data: "pelaporan" }, description: error.message || "membuat laporan" });
		return false;
	}
};

export const addStatus = async ({ number, ptId }, data) => {
	try {
		const myHeaders = new Headers();
		myHeaders.append("Content-Type", "application/json");
		const raw = JSON.stringify(data);
		const res = await fetch(`http://localhost:5000/pelaporan/status/add?number=${number}&ptId=${ptId}`, {
			method: "POST",
			body: raw,
			headers: myHeaders,
		});
		return await res.json();
	} catch (error) {
		console.log("error", error);
		return false;
	}
};
