import api from "../api";
import Constant from "../library/Constant";

const handleResponse = (response) => {
    // 1. Handling Sukses
    if (response.ok && response.data?.status === "success") {
        return response.data.data;
    }

    // 2. Ambil pesan asli
    const serverMessage = response.data?.message || response.data?.error || response.problem || "Gagal";

    // 3. Masking bahasa teknis backend
    let finalMessage = serverMessage;
    if (typeof serverMessage === 'string' && (
        serverMessage.includes("java.lang") || 
        serverMessage.includes("FormatException") ||
        serverMessage.includes("sql")
    )) {
        finalMessage = "Terjadi kesalahan format data pada sistem.";
    }

    const error = new Error(finalMessage);
    error.tipe = (response.status >= 400 && response.status < 500) ? 'warning' : 'error';
    error.isApiError = true;
    error.originalMessage = serverMessage;
    
    throw error;
};

/**
 * Wrapper agar komponen bisa memilih mau pakai data saja atau errornya juga.
 * Menghilangkan kebutuhan try-catch di komponen.
 */
const wrapService = (promise) => {
    return promise
        .then(res => {
            return { data: handleResponse(res), error: null };
        })
        .catch((err) => {
            console.error("API_LOG:", err.originalMessage || err.message);
            return { 
                data: null, 
                error: { message: err.message, tipe: err.tipe } 
            };
        });
};

// --- EXPORTED SERVICES ---

export const fetchMenuPermission = (menuName) => wrapService(api.create().getPermission({ menu: menuName }));
export const fetchDetailRole = (roleId) => wrapService(api.create().getDetailRole(roleId));
export const fetchDetailUser = () => {
    const userId = localStorage.getItem(Constant.USER);
    return wrapService(api.create().getDetailUser(userId));
};
export const fetchApprover = () => wrapService(api.create().checkApprover());
export const fetchLastPeriod = (companyId) => wrapService(api.create().getLastPeriod(companyId));
export const fetchRevision = (payload) => wrapService(api.create().getRevision(payload));
export const fetchSubmission = (payload) => wrapService(api.create().getSubmission(payload));

export const fetchListApprover = (report, monthlyReportId) => {
    return wrapService(api.create().getListApprover(report, monthlyReportId));
}

export const fetchDetailReportCF = (payload) => wrapService(api.create().getDetailReportCF(payload));
export const fetchPLID = (payload) => wrapService(api.create().getPLID(payload));
export const fetchHierarkiCreateReportPLMB = (payload) => wrapService(api.create().getHierarkiCreateReportPLMB(payload));
export const fetchFRID = (payload) => wrapService(api.create().getFRID(payload));
export const fetchDownloadFile = (payload) => wrapService(api.create().createDownloadFile(payload));
export const fetchZipReport = (downloadedFileReportId) => wrapService(api.create().createZipReport(downloadedFileReportId));