"use client";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { useAuth } from "./useAuth.js";
import { ApiError } from "../lib/api/api-error.js";
const MEDIA_QUERY_KEY = "media";
const MEDIA_TAGS_QUERY_KEY = "media-tags";
function useMediaList(options = {}) {
  const { user } = useAuth();
  return useQuery({
    queryKey: [MEDIA_QUERY_KEY, "list", options],
    queryFn: async () => {
      var _a, _b;
      const params = new URLSearchParams();
      if (options.limit) params.set("limit", String(options.limit));
      if (options.offset) params.set("offset", String(options.offset));
      if (options.orderBy) params.set("orderBy", options.orderBy);
      if (options.orderDir) params.set("orderDir", options.orderDir);
      if (options.type && options.type !== "all") params.set("type", options.type);
      if (options.search) params.set("search", options.search);
      if (options.status) params.set("status", options.status);
      if ((_a = options.tagIds) == null ? void 0 : _a.length) params.set("tagIds", options.tagIds.join(","));
      if ((_b = options.tagSlugs) == null ? void 0 : _b.length) params.set("tagSlugs", options.tagSlugs.join(","));
      const res = await fetch(`/api/v1/media?${params}`);
      if (!res.ok) {
        throw await ApiError.fromResponse(res, "Failed to fetch media");
      }
      const json = await res.json();
      return json.data;
    },
    enabled: !!user,
    staleTime: 1e3 * 60 * 5
    // 5 minutes
  });
}
function useMediaItem(id) {
  const { user } = useAuth();
  return useQuery({
    queryKey: [MEDIA_QUERY_KEY, "item", id],
    queryFn: async () => {
      if (!id) throw new Error("Media ID is required");
      const res = await fetch(`/api/v1/media/${id}`);
      if (!res.ok) {
        throw await ApiError.fromResponse(res, res.status === 404 ? "Media not found" : "Failed to fetch media");
      }
      const json = await res.json();
      return json.data;
    },
    enabled: !!user && !!id
  });
}
function useUpdateMedia() {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: async ({ id, data }) => {
      const res = await fetch(`/api/v1/media/${id}`, {
        method: "PATCH",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(data)
      });
      if (!res.ok) {
        throw await ApiError.fromResponse(res, "Failed to update media");
      }
      const json = await res.json();
      return json.data;
    },
    onSuccess: (updatedMedia) => {
      queryClient.invalidateQueries({ queryKey: [MEDIA_QUERY_KEY, "list"] });
      queryClient.setQueryData([MEDIA_QUERY_KEY, "item", updatedMedia.id], updatedMedia);
    }
  });
}
function useDeleteMedia() {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: async (id) => {
      const res = await fetch(`/api/v1/media/${id}`, {
        method: "DELETE"
      });
      if (!res.ok) {
        throw await ApiError.fromResponse(res, "Failed to delete media");
      }
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: [MEDIA_QUERY_KEY] });
    }
  });
}
function useMediaTags() {
  const { user } = useAuth();
  return useQuery({
    queryKey: [MEDIA_TAGS_QUERY_KEY],
    queryFn: async () => {
      const res = await fetch("/api/v1/media-tags");
      if (!res.ok) {
        throw await ApiError.fromResponse(res, "Failed to fetch media tags");
      }
      const json = await res.json();
      return json.data || [];
    },
    enabled: !!user,
    staleTime: 1e3 * 60 * 10
    // 10 minutes - tags change infrequently
  });
}
function useMediaItemTags(mediaId) {
  const { user } = useAuth();
  return useQuery({
    queryKey: [MEDIA_TAGS_QUERY_KEY, "item", mediaId],
    queryFn: async () => {
      if (!mediaId) throw new Error("Media ID is required");
      const res = await fetch(`/api/v1/media/${mediaId}/tags`);
      if (!res.ok) {
        throw await ApiError.fromResponse(res, "Failed to fetch media tags");
      }
      const json = await res.json();
      return json.data || [];
    },
    enabled: !!user && !!mediaId
  });
}
function useAddMediaTag() {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: async ({ mediaId, tagId }) => {
      const res = await fetch(`/api/v1/media/${mediaId}/tags`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ tagId })
      });
      if (!res.ok) {
        throw await ApiError.fromResponse(res, "Failed to add tag");
      }
      const json = await res.json();
      return json.data || [];
    },
    onSuccess: (_, { mediaId }) => {
      queryClient.invalidateQueries({ queryKey: [MEDIA_TAGS_QUERY_KEY, "item", mediaId] });
    }
  });
}
function useCreateMediaTag() {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: async (name) => {
      const res = await fetch("/api/v1/media-tags", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ name })
      });
      if (!res.ok) {
        throw await ApiError.fromResponse(res, "Failed to create tag");
      }
      const json = await res.json();
      return json.data;
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: [MEDIA_TAGS_QUERY_KEY] });
    }
  });
}
function useRemoveMediaTag() {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: async ({ mediaId, tagId }) => {
      const res = await fetch(`/api/v1/media/${mediaId}/tags?tagId=${tagId}`, {
        method: "DELETE"
      });
      if (!res.ok) {
        throw await ApiError.fromResponse(res, "Failed to remove tag");
      }
    },
    onSuccess: (_, { mediaId }) => {
      queryClient.invalidateQueries({ queryKey: [MEDIA_TAGS_QUERY_KEY, "item", mediaId] });
    }
  });
}
export {
  useAddMediaTag,
  useCreateMediaTag,
  useDeleteMedia,
  useMediaItem,
  useMediaItemTags,
  useMediaList,
  useMediaTags,
  useRemoveMediaTag,
  useUpdateMedia
};
