// useSharedFolders.ts — M6.5 Step 4 mailbox share hooks.

import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { apiClient } from "../apiClient";

export interface Rights {
  mayRead?: boolean;
  mayAddItems?: boolean;
  mayRemoveItems?: boolean;
  mayCreateChild?: boolean;
  mayRename?: boolean;
  mayDelete?: boolean;
  mayAdmin?: boolean;
  maySubmit?: boolean;
}

export interface MailboxShare {
  id: string;
  owner_mailbox_id: string;
  owner_mailbox_email?: string;
  shared_with_mailbox_id: string;
  shared_with_mailbox_email?: string;
  rights: Rights;
  created_at: string;
}

const QK_ALL = ["mail_shares", "all"];

export function useAllShares() {
  return useQuery({
    queryKey: QK_ALL,
    queryFn: async () => {
      const { data } = await apiClient.get<{ data: MailboxShare[]; total: number }>("/mail/shares");
      return data.data ?? [];
    },
  });
}

export function useCreateShare() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: async ({
      ownerMailboxID,
      sharedWithMailboxID,
      rights,
    }: {
      ownerMailboxID: string;
      sharedWithMailboxID: string;
      rights: Rights;
    }) => {
      const { data } = await apiClient.post<MailboxShare>(
        `/mailboxes/${ownerMailboxID}/shares`,
        { shared_with_mailbox_id: sharedWithMailboxID, rights },
      );
      return data;
    },
    onSuccess: () => qc.invalidateQueries({ queryKey: QK_ALL }),
  });
}

export function useDeleteShare() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: async ({
      ownerMailboxID,
      shareID,
    }: {
      ownerMailboxID: string;
      shareID: string;
    }) => {
      await apiClient.delete(`/mailboxes/${ownerMailboxID}/shares/${shareID}`);
    },
    onSuccess: () => qc.invalidateQueries({ queryKey: QK_ALL }),
  });
}
