import { reactive, ref } from "vue";
import { useMutation } from "@tanstack/vue-query";
import { requests } from "../../../api/agent";
import { useToast } from "../../../utils/composables/use-toast";
import { BaseComposableOption } from "../../../types/composable.types";
import {
  ShareShootingDTO,
  ShootingDTO,
} from "@studio-m/app-types/src/shooting.types";

export const useShareShooting = (
  options: BaseComposableOption<ShootingDTO> = {}
) => {
  const { success, error } = useToast();

  const emails = ref<string>("");

  const payload: ShareShootingDTO = reactive({
    emails: [],
    message: "",
    name: "",
    shootingId: options.payload?.id || "",
  });

  const parseEmails = () =>
    emails.value
      .split(',')
      .map((email) => email.trim())
      .filter((email) => email.length);

  const mutation = useMutation({
    mutationFn: async (shootingId: string) => {
      payload.emails = parseEmails();
      return await requests.post(`shootings/${shootingId}/share`, payload);
    },
    onSuccess: () => {
      success({ message: "Le shooting a été partagé avec succès" });
      options.onSuccess?.();
    },
    onError: () => {
      error({ message: "Une erreur est survenue lors du partage du shooting" });
      options.onError?.();
    },
    retry: false,
  });

  const shareShooting = (shootingId: string) => {
    return mutation.mutateAsync(shootingId);
  };

  const isPreviewing = ref(false);
  const previewShareShooting = async (
    shootingId: string,
    mode: "guest" | "customer"
  ) => {
    try {
      isPreviewing.value = true;
      payload.emails = parseEmails();
      return await requests.post(`shootings/${shootingId}/share/preview`, {
        ...payload,
        mode,
      });
    } finally {
      isPreviewing.value = false;
    }
  };

  return {
    shareShooting,
    isSharing: mutation.isPending,
    isPreviewing,
    previewShareShooting,
    payload,
    emails,
  };
};
