"use server";

// import { serverFetchWithNoContent } from '@/app/utils/fetchUtil';
// import { BASE_API_URL } from "@/config/api";
import { serverFetch, serverFetchWithNoContent } from "../../../utils/fetchUtil";
import { BASE_API_URL } from "../../../../config/api";

export interface M18ImportPoForm {
  modifiedDateFrom: string;
  modifiedDateTo: string;
  dDateFrom: string;
  dDateTo: string;
}

export interface M18ImportDoForm {
  modifiedDateFrom: string;
  modifiedDateTo: string;
  dDateFrom: string;
  dDateTo: string;
}

export interface M18ImportPqForm {
  modifiedDateFrom: string;
  modifiedDateTo: string;
}

export interface M18ImportMasterDataForm {
  modifiedDateFrom: string;
  modifiedDateTo: string;
}

export interface M18ImportTestingForm {
  po: M18ImportPoForm;
  do: M18ImportDoForm;
  pq: M18ImportPqForm;
  masterData: M18ImportMasterDataForm;
}

export const testM18ImportPo = async (data: M18ImportPoForm) => {
  return serverFetchWithNoContent(`${BASE_API_URL}/m18/po`, {
    method: "POST",
    body: JSON.stringify(data),
    headers: { "Content-Type": "application/json" },
  });
};

export const testM18ImportDo = async (data: M18ImportDoForm) => {
  return serverFetchWithNoContent(`${BASE_API_URL}/m18/do`, {
    method: "POST",
    body: JSON.stringify(data),
    headers: { "Content-Type": "application/json" },
  });
};

export const testM18ImportPq = async (data: M18ImportPqForm) => {
  const token = localStorage.getItem("accessToken");
  
  return serverFetchWithNoContent(`${BASE_API_URL}/m18/pq`, {
    method: "POST",
    body: JSON.stringify(data),
    headers: { "Content-Type": "application/json", "Authorization": `Bearer ${token}`, },
    
  });
};

export const testM18ImportMasterData = async (
  data: M18ImportMasterDataForm,
) => {
  return serverFetchWithNoContent(`${BASE_API_URL}/m18/master-data`, {
    method: "POST",
    body: JSON.stringify(data),
    headers: { "Content-Type": "application/json" },
  });
};

export const triggerScheduler = async (type: 'po' | 'do1' | 'do2' | 'master-data' | 'refresh-cron') => {
    try {
        // IMPORTANT: 'refresh-cron' is a direct endpoint /api/scheduler/refresh-cron
        // Others are /api/scheduler/trigger/{type}
        const path = type === 'refresh-cron' 
            ? 'refresh-cron' 
            : `trigger/${type}`;

        const url = `${BASE_API_URL}/scheduler/${path}`;
        
        console.log("Fetching URL:", url);

        const response = await serverFetch(url, {
            method: "GET",
            cache: "no-store",
        });

        if (!response.ok) throw new Error(`Failed: ${response.status}`);

        return await response.text();
    } catch (error) {
        console.error("Scheduler Action Error:", error);
        return null;
    }
};

export const refreshCronSchedules = async () => {
    // Simply reuse the triggerScheduler logic to avoid duplication
    // or call serverFetch directly as shown below:
    try {
        const response = await serverFetch(`${BASE_API_URL}/scheduler/refresh-cron`, {
            method: "GET",
            cache: "no-store",
        });

        if (!response.ok) throw new Error(`Failed to refresh: ${response.status}`);

        return await response.text();
    } catch (error) {
        console.error("Refresh Cron Error:", error);
        return "Refresh failed. Check server logs.";
    }
};