import { ServerRequest } from "@/lib/actions";
import updateFileContent from "@/services/files/updateFileContent";
import { toast } from "sonner";

type SaveFileProps = {
  path: string;
  file: { content?: string; type?: string };
  params: any;
  dict: Dictionary;
};
export default async function handleSaveFile({
  path,
  file,
  params,
  dict,
}: SaveFileProps) {
  const promise = new Promise(async (resolve, reject) => {
    const formData = new FormData();
    formData.append("dir", path!);
    formData.append("file", file?.content!);
    formData.append("project-name", params.name as string);
    const result = await ServerRequest(updateFileContent(formData));

    if (!result.operation) {
      return reject(result);
    }
    return resolve(result);
  });
  toast.promise(promise, {
    loading: dict.alerts.save_file.loading,
    duration: 1000,
    success: ({ message }: any) => message,
    error: ({ message }: any) => message,
  });
}
