/**
 * User CRUD hooks.
 */

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

// ── Types matching backend schemas ──

export interface UserResponse {
  id: string;
  email: string;
  name: string;
  first_name: string | null;
  last_name: string | null;
  avatar_url: string | null;
  role: string;
  role_id: string | null;
  is_active: boolean;
  tenant_id: string;
}

export interface UserCreate {
  email: string;
  name: string;
  password: string;
  role?: string;
  role_id?: string | null;
  is_active?: boolean;
}

export interface UserUpdate {
  name?: string;
  first_name?: string;
  last_name?: string;
  email?: string;
  avatar_url?: string | null;
  role?: string;
  role_id?: string | null;
  is_active?: boolean;
  current_password?: string;
  new_password?: string;
}

export function useUsers(page = 1, pageSize = 25) {
  return useQuery({
    queryKey: ['users', page, pageSize],
    queryFn: () =>
      apiGet<PaginatedResponse<UserResponse>>(`/users?page=${page}&page_size=${pageSize}`),
  });
}

export function useUser(id?: string) {
  return useQuery({
    queryKey: ['users', id],
    queryFn: () => apiGet<UserResponse>(`/users/${id}`),
    enabled: !!id,
  });
}

export function useCreateUser() {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: (data: UserCreate) => apiPost('/users', data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['users'] });
    },
  });
}

export function useUpdateUser() {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: ({ id, data }: { id: string; data: UserUpdate }) =>
      apiPatch(`/users/${id}`, data),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['users'] });
    },
  });
}

export function useDeleteUser() {
  const queryClient = useQueryClient();
  return useMutation({
    mutationFn: (id: string) => apiDelete(`/users/${id}`),
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ['users'] });
    },
  });
}
