/**
 * Plugin management hooks: list, install, activate, deactivate, uninstall, upload, install-url.
 */

import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { apiGet, apiPost, apiDelete } from './client';

// ── Types matching backend schemas ──

export interface Plugin {
  name: string;
  display_name: string;
  version: string;
  status: 'discovered' | 'installed' | 'active' | 'inactive';
  installed: boolean;
  active: boolean;
  description: string;
  dependencies: string[];
  events: string[];
  migrations: string[];
  permissions: string[];
}

export interface PluginListResponse {
  plugins: Plugin[];
  total: number;
}

export interface PluginActionResponse {
  name: string;
  display_name: string;
  version: string;
  status: string;
  installed: boolean;
  active: boolean;
  dropped_tables: string[];
  message: string;
}

export function usePlugins() {
  return useQuery({
    queryKey: ['plugins'],
    queryFn: async () => {
      const data = await apiGet<PluginListResponse>('/plugins');
      return data.plugins;
    },
  });
}

export function useInstallPlugin() {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: (name: string) => apiPost<PluginActionResponse>(`/plugins/${name}/install`),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['plugins'] });
    },
  });
}

export function useActivatePlugin() {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: (name: string) => apiPost<PluginActionResponse>(`/plugins/${name}/activate`),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['plugins'] });
    },
  });
}

export function useDeactivatePlugin() {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: (name: string) => apiPost<PluginActionResponse>(`/plugins/${name}/deactivate`),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['plugins'] });
    },
  });
}

export function useUninstallPlugin() {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: ({ name, removeData }: { name: string; removeData: boolean }) =>
      apiDelete<PluginActionResponse>(`/plugins/${name}?remove_data=${removeData}`),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['plugins'] });
    },
  });
}

export function useUploadPlugin() {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: async (file: File) => {
      const formData = new FormData();
      formData.append('file', file);
      const { default: apiClient } = await import('./client');
      const res = await apiClient.post('/plugins/upload', formData, {
        headers: { 'Content-Type': 'multipart/form-data' },
      });
      return res.data as PluginActionResponse;
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['plugins'] });
    },
  });
}

export function useInstallPluginFromUrl() {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: async (url: string) => {
      const { default: apiClient } = await import('./client');
      const res = await apiClient.post('/plugins/install-url', { url });
      return res.data as PluginActionResponse;
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['plugins'] });
    },
  });
}
