"use client";

import { keepPreviousData, useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { api } from "@/lib/api";
import type { ApiResponse, PaginationMeta } from "@/types";

export type QueryParams = Record<string, string | number | boolean | null | undefined>;

/** Buang parameter kosong agar URL bersih & cache key stabil. */
export function cleanParams(params: QueryParams = {}): Record<string, string | number | boolean> {
  return Object.fromEntries(
    Object.entries(params).filter(([, v]) => v !== undefined && v !== null && v !== "" && v !== "all"),
  ) as Record<string, string | number | boolean>;
}

/**
 * Hooks CRUD generik untuk resource REST Laravel (index/show/store/update/destroy).
 * Dipakai untuk Area, Paket, Pengguna; Pelanggan punya hook tambahan sendiri.
 */
export function createResourceHooks<T extends { id: number }, TInput = Partial<T>>(key: readonly string[], path: string) {
  function useList(params: QueryParams = {}, enabled = true) {
    const clean = cleanParams(params);
    return useQuery({
      queryKey: [...key, "list", clean],
      queryFn: async () => (await api.get<ApiResponse<T[], PaginationMeta>>(path, { params: clean })).data,
      placeholderData: keepPreviousData,
      enabled,
    });
  }

  /** Semua data tanpa paginasi (untuk dropdown). */
  function useAll(params: QueryParams = {}, enabled = true) {
    const clean = cleanParams({ ...params, all: 1 });
    return useQuery({
      queryKey: [...key, "all", clean],
      queryFn: async () => (await api.get<ApiResponse<T[], null>>(path, { params: clean })).data.data,
      staleTime: 5 * 60 * 1000,
      enabled,
    });
  }

  function useOne(id: number | string | undefined) {
    return useQuery({
      queryKey: [...key, "detail", String(id)],
      queryFn: async () => (await api.get<ApiResponse<T, unknown>>(`${path}/${id}`)).data,
      enabled: id !== undefined && id !== "",
    });
  }

  function useCreate() {
    const qc = useQueryClient();
    return useMutation({
      mutationFn: async (input: TInput) => (await api.post<ApiResponse<T, null>>(path, input)).data,
      onSuccess: () => qc.invalidateQueries({ queryKey: key }),
    });
  }

  function useUpdate() {
    const qc = useQueryClient();
    return useMutation({
      mutationFn: async ({ id, input }: { id: number; input: TInput }) =>
        (await api.put<ApiResponse<T, null>>(`${path}/${id}`, input)).data,
      onSuccess: () => qc.invalidateQueries({ queryKey: key }),
    });
  }

  function useDelete() {
    const qc = useQueryClient();
    return useMutation({
      mutationFn: async (id: number) => (await api.delete<ApiResponse<null, null>>(`${path}/${id}`)).data,
      onSuccess: () => qc.invalidateQueries({ queryKey: key }),
    });
  }

  return { useList, useAll, useOne, useCreate, useUpdate, useDelete };
}
