'use client';

import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { api } from '@/lib/api';

// ---------------------------------------------------------------------------
// Types
// ---------------------------------------------------------------------------

export type SettingValueType = 'string' | 'number' | 'boolean' | 'json';

export interface SystemSetting {
  key: string;
  value: string;
  category: string;
  description: string;
  valueType: SettingValueType;
  isSecret: boolean;
}

export interface SystemSettingsResponse {
  settings: SystemSetting[];
  categories: string[];
}

export interface UpdateSettingPayload {
  value: string;
}

export interface BulkUpdatePayload {
  settings: { key: string; value: string }[];
}

// ---------------------------------------------------------------------------
// Query key factory
// ---------------------------------------------------------------------------

export const systemSettingsKeys = {
  all: ['system-settings'] as const,
  list: (category?: string) =>
    [...systemSettingsKeys.all, 'list', category] as const,
  detail: (key: string) => [...systemSettingsKeys.all, 'detail', key] as const,
};

// ---------------------------------------------------------------------------
// Fetch functions
// ---------------------------------------------------------------------------

async function fetchSystemSettings(category?: string): Promise<SystemSettingsResponse> {
  const params: Record<string, string | undefined> = {};
  if (category) params.category = category;
  return api.get<SystemSettingsResponse>('/system-settings', { params });
}

async function updateSetting(key: string, value: string): Promise<SystemSetting> {
  return api.put<SystemSetting>(`/system-settings/${encodeURIComponent(key)}`, { value });
}

async function bulkUpdateSettings(payload: BulkUpdatePayload): Promise<SystemSetting[]> {
  return api.put<SystemSetting[]>('/system-settings/bulk', payload);
}

// ---------------------------------------------------------------------------
// Hooks
// ---------------------------------------------------------------------------

/**
 * Fetch all system settings, optionally filtered by category.
 */
export function useSystemSettings(category?: string) {
  return useQuery({
    queryKey: systemSettingsKeys.list(category),
    queryFn: () => fetchSystemSettings(category),
    staleTime: 60_000,
  });
}

/**
 * Mutation: update a single setting by key.
 */
export function useUpdateSetting() {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: ({ key, value }: { key: string; value: string }) =>
      updateSetting(key, value),
    onSuccess: () => {
      void queryClient.invalidateQueries({ queryKey: systemSettingsKeys.all });
    },
  });
}

/**
 * Mutation: update multiple settings at once.
 */
export function useBulkUpdateSettings() {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: (payload: BulkUpdatePayload) => bulkUpdateSettings(payload),
    onSuccess: () => {
      void queryClient.invalidateQueries({ queryKey: systemSettingsKeys.all });
    },
  });
}
