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

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

export function useProjects() {
  return useQuery({
    queryKey: PROJECTS_KEY,
    queryFn: projectsApi.list,
  });
}

export function useProject(id: string) {
  return useQuery({
    queryKey: projectKey(id),
    queryFn: () => projectsApi.get(id),
    enabled: !!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) }),
  });
}
