import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { apiFetch } from "./client";
import type { User } from "@/types/api";

export type UserPayload = {
  email: string;
  name: string;
  department: string;
  role: string;
  is_active: boolean;
  password?: string;
};

export type ImportResult = {
  success: number;
  failed: number;
  errors: string[];
};

export function useListUsers() {
  return useQuery({
    queryKey: ["users"],
    queryFn: () => apiFetch<{ data: User[] }>("/v1/admin/users").then((r) => r.data),
  });
}

export function useCreateUser() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: (body: UserPayload) =>
      apiFetch<User>("/v1/admin/users", { method: "POST", body: JSON.stringify(body) }),
    onSuccess: () => qc.invalidateQueries({ queryKey: ["users"] }),
  });
}

export function useUpdateUser() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: ({ id, ...body }: UserPayload & { id: string }) =>
      apiFetch<User>(`/v1/admin/users/${id}`, { method: "PUT", body: JSON.stringify(body) }),
    onSuccess: () => qc.invalidateQueries({ queryKey: ["users"] }),
  });
}

export function useDeleteUser() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: (id: string) =>
      apiFetch<void>(`/v1/admin/users/${id}`, { method: "DELETE" }),
    onSuccess: () => qc.invalidateQueries({ queryKey: ["users"] }),
  });
}

export function useImportUsers() {
  const qc = useQueryClient();
  return useMutation({
    mutationFn: async (users: UserPayload[]): Promise<ImportResult> => {
      const result: ImportResult = { success: 0, failed: 0, errors: [] };
      for (const user of users) {
        try {
          await apiFetch<User>("/v1/admin/users", { method: "POST", body: JSON.stringify(user) });
          result.success++;
        } catch {
          result.failed++;
          result.errors.push(user.email);
        }
      }
      return result;
    },
    onSuccess: () => qc.invalidateQueries({ queryKey: ["users"] }),
  });
}
