import { create } from 'zustand';
import { api } from '../lib/api.ts';

export interface ModerationState {
  isLoading: boolean;
  error: string | null;
  kickMember: (serverId: string, userId: string, reason?: string) => Promise<void>;
  banMember: (serverId: string, userId: string, reason?: string) => Promise<void>;
  unbanMember: (serverId: string, userId: string) => Promise<void>;
  muteMember: (serverId: string, userId: string, durationSeconds: number) => Promise<void>;
  clearError: () => void;
}

export const useModerationStore = create<ModerationState>((set) => ({
  isLoading: false,
  error: null,

  kickMember: async (serverId, userId, reason) => {
    set({ isLoading: true, error: null });
    try {
      await api.post(`/servers/${serverId}/members/${userId}/kick`, { reason });
      set({ isLoading: false });
    } catch (error) {
      const message = error instanceof Error ? error.message : 'Failed to kick member';
      set({ isLoading: false, error: message });
      throw error;
    }
  },

  banMember: async (serverId, userId, reason) => {
    set({ isLoading: true, error: null });
    try {
      await api.post(`/servers/${serverId}/members/${userId}/ban`, { reason });
      set({ isLoading: false });
    } catch (error) {
      const message = error instanceof Error ? error.message : 'Failed to ban member';
      set({ isLoading: false, error: message });
      throw error;
    }
  },

  unbanMember: async (serverId, userId) => {
    set({ isLoading: true, error: null });
    try {
      await api.post(`/servers/${serverId}/members/${userId}/unban`, {});
      set({ isLoading: false });
    } catch (error) {
      const message = error instanceof Error ? error.message : 'Failed to unban member';
      set({ isLoading: false, error: message });
      throw error;
    }
  },

  muteMember: async (serverId, userId, durationSeconds) => {
    set({ isLoading: true, error: null });
    try {
      await api.post(`/servers/${serverId}/members/${userId}/mute`, { duration_seconds: durationSeconds });
      set({ isLoading: false });
    } catch (error) {
      const message = error instanceof Error ? error.message : 'Failed to mute member';
      set({ isLoading: false, error: message });
      throw error;
    }
  },

  clearError: () => set({ error: null }),
}));
