import { useMutation } from "@tanstack/react-query";
import { toast } from "react-hot-toast";
import { APIUrlGenerator } from "@/utils/baseHttpService";
import { API_ROUTES } from "@/constant/routes";
import { httpPostRequest, httpDeleteRequest } from "@/utils/baseHttpService";

interface UploadResponse {
  file: {
    id: number;
    url: string;
    name: string;
    original_name: string;
    serve_key: string;
    size: number;
    mime_type: string;
    created_at: string;
    updated_at: string;
  };
}

export const useFileUpload = () => {
  return useMutation({
    mutationFn: async (file: File): Promise<{ id: string; url: string; mimeType?: string }> => {
      const formData = new FormData();
      formData.append("file", file);
      formData.append("name", "uploaded-file");

      console.log("Uploading file:", file.name);

      const response = await httpPostRequest<UploadResponse>(
        APIUrlGenerator(API_ROUTES.UPLOAD_FILE),
        formData,
        {
          headers: {
            "Content-Type": "multipart/form-data",
          },
        }
      );

      console.log("Upload response:", response);

      if (!response.data?.file) {
        throw new Error("Invalid upload response");
      }

      return {
        id: response.data.file.id.toString(),
        url: response.data.file.url,
        mimeType: response.data.file.mime_type,
      };
    },
    onError: (error: any) => {
      console.error("File upload error:", error);
      toast.error(error?.message || "خطا در آپلود فایل");
    },
  });
};

export const useFileDelete = () => {
  return useMutation({
    mutationFn: async (fileId: string) => {
      const response = await httpDeleteRequest(
        APIUrlGenerator(API_ROUTES.DELETE_FILE(fileId))
      );
      return response.data;
    },
    onSuccess: () => {
      toast.success("فایل با موفقیت حذف شد");
    },
    onError: (error: any) => {
      console.error("File delete error:", error);
      toast.error(error?.message || "خطا در حذف فایل");
    },
  });
};
