'use client';

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

// ============================================================
// Types matching backend DTOs and service response shapes
// ============================================================

export interface CredentialListItem {
  id: string;
  type: string;
  name: string;
  isActive: boolean;
  lastUsed: string | null;
  lastSync: string | null;
  syncStatus: string;
  syncError: string | null;
  createdAt: string;
  updatedAt: string;
}

export interface CredentialDetail extends CredentialListItem {
  credentials: Record<string, string>;
}

export interface PaginatedCredentials {
  data: CredentialListItem[];
  meta: {
    total: number;
    page: number;
    limit: number;
    totalPages: number;
  };
}

export interface CreateCredentialPayload {
  type: string;
  name: string;
  credentials: Record<string, string>;
}

export interface UpdateCredentialPayload {
  name?: string;
  credentials?: Record<string, string>;
  isActive?: boolean;
}

export interface TestConnectionResult {
  success: boolean;
  message: string;
  latency?: number;
}

// ============================================================
// Query key factory
// ============================================================

export const credentialKeys = {
  all: ['credentials'] as const,
  list: (type?: string) => [...credentialKeys.all, 'list', type] as const,
  detail: (id: string) => [...credentialKeys.all, 'detail', id] as const,
};

// ============================================================
// Hooks
// ============================================================

/**
 * Fetch all credentials, optionally filtered by integration type.
 * Does NOT include decrypted credential secrets.
 */
export function useCredentials(type?: string) {
  return useQuery({
    queryKey: credentialKeys.list(type),
    queryFn: () =>
      api.get<PaginatedCredentials>('/integrations/credentials', {
        params: type
          ? { type: type.toUpperCase(), limit: 100 }
          : { limit: 100 },
      }),
    staleTime: 30_000,
  });
}

/**
 * Fetch a single credential by ID with decrypted secrets.
 * staleTime is 0 so the decrypted values are always fresh.
 */
export function useCredentialDetail(id: string | null) {
  return useQuery({
    queryKey: credentialKeys.detail(id!),
    queryFn: () =>
      api.get<CredentialDetail>(`/integrations/credentials/${id}`),
    enabled: !!id,
    staleTime: 0,
  });
}

/** Create a new integration credential. */
export function useCreateCredential() {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: (data: CreateCredentialPayload) =>
      api.post<CredentialListItem>('/integrations/credentials', data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: credentialKeys.all });
    },
  });
}

/** Update name, credentials payload, or isActive flag. */
export function useUpdateCredential() {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: ({ id, ...data }: UpdateCredentialPayload & { id: string }) =>
      api.put<CredentialListItem>(`/integrations/credentials/${id}`, data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: credentialKeys.all });
    },
  });
}

/** Soft-delete (deactivate) a credential. */
export function useDeleteCredential() {
  const queryClient = useQueryClient();

  return useMutation({
    mutationFn: (id: string) =>
      api.delete<CredentialListItem>(`/integrations/credentials/${id}`),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: credentialKeys.all });
    },
  });
}

/** Test the connection for a saved credential by its ID. */
export function useTestCredentialConnection() {
  return useMutation({
    mutationFn: (id: string) =>
      api.post<TestConnectionResult>(
        `/integrations/credentials/${id}/test`,
      ),
  });
}
