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

export interface Environment {
  id: string;
  slug: string;
  displayName: string;
  production: boolean;
  enabled: boolean;
  defaultContainerConfig: Record<string, unknown>;
  jarRetentionCount: number | null;
  color: string;
  createdAt: string;
}

export interface CreateEnvironmentRequest {
  slug: string;
  displayName: string;
  production: boolean;
}

export interface UpdateEnvironmentRequest {
  displayName: string;
  production: boolean;
  enabled: boolean;
  color?: string;
}

export function useEnvironments() {
  return useQuery({
    queryKey: ['admin', 'environments'],
    queryFn: () => adminFetch<Environment[]>('/environments'),
  });
}

export function useCreateEnvironment() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: (req: CreateEnvironmentRequest) =>
      adminFetch<Environment>('/environments', {
        method: 'POST',
        body: JSON.stringify(req),
      }),
    onSuccess: () => qc.invalidateQueries({ queryKey: ['admin', 'environments'] }),
  });
}

export function useUpdateEnvironment() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: ({ slug, ...req }: UpdateEnvironmentRequest & { slug: string }) =>
      adminFetch<Environment>(`/environments/${slug}`, {
        method: 'PUT',
        body: JSON.stringify(req),
      }),
    onSuccess: () => qc.invalidateQueries({ queryKey: ['admin', 'environments'] }),
  });
}

export function useUpdateDefaultContainerConfig() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: ({ slug, config }: { slug: string; config: Record<string, unknown> }) =>
      adminFetch<Environment>(`/environments/${slug}/default-container-config`, {
        method: 'PUT',
        body: JSON.stringify(config),
      }),
    onSuccess: () => qc.invalidateQueries({ queryKey: ['admin', 'environments'] }),
  });
}

export function useUpdateJarRetention() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: ({ slug, jarRetentionCount }: { slug: string; jarRetentionCount: number | null }) =>
      adminFetch<Environment>(`/environments/${slug}/jar-retention`, {
        method: 'PUT',
        body: JSON.stringify({ jarRetentionCount }),
      }),
    onSuccess: () => qc.invalidateQueries({ queryKey: ['admin', 'environments'] }),
  });
}

export function useDeleteEnvironment() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: (slug: string) =>
      adminFetch<void>(`/environments/${slug}`, { method: 'DELETE' }),
    onSuccess: () => qc.invalidateQueries({ queryKey: ['admin', 'environments'] }),
  });
}
