import { trpc } from '@/lib/trpc';
import { useNotify } from '@/hooks/useNotify';

const MAX_SIZE = 50 * 1024 * 1024;

export function useTaskAttachments(taskId: string | null) {
  const utils = trpc.useUtils();
  const { notify, notifyError } = useNotify();

  const list = trpc.taskAttachments.list.useQuery(
    { taskId: taskId ?? '' },
    { enabled: !!taskId },
  );
  const pick = trpc.taskAttachments.pick.useMutation();
  const create = trpc.taskAttachments.create.useMutation({
    onSuccess: () => taskId && void utils.taskAttachments.list.invalidate({ taskId }),
    onError: (err) => notifyError('toast.attachment.createError', err),
  });
  const remove = trpc.taskAttachments.delete.useMutation({
    onSuccess: () => taskId && void utils.taskAttachments.list.invalidate({ taskId }),
  });
  const open = trpc.taskAttachments.open.useMutation();

  async function addFiles() {
    if (!taskId) return;
    const picked = await pick.mutateAsync();
    for (const f of picked) {
      if (f.size > MAX_SIZE) {
        notify('warning', 'toast.attachment.tooLarge', { values: { filename: f.name } });
        continue;
      }
      await create.mutateAsync({
        taskId,
        sourcePath: f.path,
        filename: f.name,
        sizeBytes: f.size,
      });
    }
  }

  return { list, addFiles, remove, open };
}
