import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { projectsApi, ProjectCreatePayload, ProjectUpdatePayload } from "../lib/api/projects";
import { useAuthStore } from "../stores/authStore";

const PROJECTS_KEY = ["projects"];
const projectKey = (id: string) => ["projects", id];

export function useProjects() {
  const isAuthReady = useAuthStore((state) => state.hasHydrated && state.isAuthenticated);
  return useQuery({
    queryKey: PROJECTS_KEY,
    queryFn: projectsApi.list,
    enabled: isAuthReady,
  });
}

export function useProject(id: string) {
  const isAuthReady = useAuthStore((state) => state.hasHydrated && state.isAuthenticated);
  return useQuery({
    queryKey: projectKey(id),
    queryFn: () => projectsApi.get(id),
    enabled: isAuthReady && !!id,
  });
}

export function useCreateProject() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: (p: ProjectCreatePayload) => projectsApi.create(p),
    onSuccess: () => qc.invalidateQueries({ queryKey: PROJECTS_KEY }),
  });
}

export function useUpdateProject(id: string) {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: (p: ProjectUpdatePayload) => projectsApi.update(id, p),
    onSuccess: () => {
      qc.invalidateQueries({ queryKey: PROJECTS_KEY });
      qc.invalidateQueries({ queryKey: projectKey(id) });
    },
  });
}

export function useDeleteProject() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: (id: string) => projectsApi.delete(id),
    onSuccess: () => qc.invalidateQueries({ queryKey: PROJECTS_KEY }),
  });
}

export function useUploadAsset(projectId: string) {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: ({ file, assetType }: { file: File; assetType?: string }) =>
      projectsApi.uploadAsset(projectId, file, assetType),
    onSuccess: () => qc.invalidateQueries({ queryKey: projectKey(projectId) }),
  });
}
