// User Admin API requests

import {
  httpGetRequest,
  httpPostRequest,
  httpPutRequest,
  httpDeleteRequest,
} from "../../../utils/baseHttpService";
import { APIUrlGenerator } from "../../../utils/baseHttpService";
import { API_ROUTES } from "../../../constant/routes";
import {
  User,
  PaginatedUsersResponse,
  UserFilters,
  CreateUserRequest,
  UpdateUserRequest,
  UpdateUserProfileRequest,
  UpdateUserAvatarRequest,
  UserActionResponse,
  UserStats,
} from "./_models";

// Get all users with pagination
export const getUsers = async (filters?: UserFilters): Promise<User[]> => {
  const queryParams: Record<string, string | number | null> = {};

  if (filters?.limit) queryParams.limit = filters.limit;
  if (filters?.offset) queryParams.offset = filters.offset;
  if (filters?.search_text) queryParams.search_text = filters.search_text;
  if (filters?.verified !== undefined)
    queryParams.verified = filters.verified ? "true" : "false";

  const response = await httpGetRequest<PaginatedUsersResponse>(
    APIUrlGenerator(API_ROUTES.GET_USERS, queryParams)
  );

  return response.data.users || [];
};

// Get user by ID
export const getUser = async (id: string): Promise<User> => {
  const response = await httpGetRequest<User>(
    APIUrlGenerator(API_ROUTES.GET_USER(id))
  );
  return response.data;
};

// Search users with filters
export const searchUsers = async (
  filters: UserFilters
): Promise<PaginatedUsersResponse> => {
  const queryParams: Record<string, string | number | null> = {};

  if (filters.verified !== undefined)
    queryParams.verified = filters.verified ? "true" : "false";
  if (filters.search_text) queryParams.search_text = filters.search_text;
  if (filters.phone_number) queryParams.phone_number = filters.phone_number;
  if (filters.email) queryParams.email = filters.email;
  if (filters.national_code) queryParams.national_code = filters.national_code;
  if (filters.limit) queryParams.limit = filters.limit;
  if (filters.offset) queryParams.offset = filters.offset;

  const response = await httpGetRequest<PaginatedUsersResponse>(
    APIUrlGenerator(API_ROUTES.SEARCH_USERS, queryParams)
  );

  return response.data;
};

// Create new user
export const createUser = async (
  userData: CreateUserRequest
): Promise<User> => {
  const response = await httpPostRequest<User>(
    APIUrlGenerator(API_ROUTES.CREATE_USER),
    userData
  );
  return response.data;
};

// Update user
export const updateUser = async (
  id: string,
  userData: UpdateUserRequest
): Promise<User> => {
  const response = await httpPutRequest<User>(
    APIUrlGenerator(API_ROUTES.UPDATE_USER(id)),
    userData
  );
  return response.data;
};

// Update user profile
export const updateUserProfile = async (
  id: string,
  userData: UpdateUserProfileRequest
): Promise<User> => {
  const response = await httpPutRequest<User>(
    APIUrlGenerator(API_ROUTES.UPDATE_USER_PROFILE(id)),
    userData
  );
  return response.data;
};

// Update user avatar
export const updateUserAvatar = async (
  id: string,
  avatarData: UpdateUserAvatarRequest
): Promise<UserActionResponse> => {
  const response = await httpPutRequest<UserActionResponse>(
    APIUrlGenerator(API_ROUTES.UPDATE_USER_AVATAR(id)),
    avatarData
  );
  return response.data;
};

// Delete user
export const deleteUser = async (id: string): Promise<UserActionResponse> => {
  const response = await httpDeleteRequest<UserActionResponse>(
    APIUrlGenerator(API_ROUTES.DELETE_USER(id))
  );
  return response.data;
};

// Verify user
export const verifyUser = async (id: string): Promise<UserActionResponse> => {
  const response = await httpPostRequest<UserActionResponse>(
    APIUrlGenerator(API_ROUTES.VERIFY_USER(id)),
    {}
  );
  return response.data;
};

// Unverify user
export const unverifyUser = async (id: string): Promise<UserActionResponse> => {
  const response = await httpPostRequest<UserActionResponse>(
    APIUrlGenerator(API_ROUTES.UNVERIFY_USER(id)),
    {}
  );
  return response.data;
};

// Get user statistics
export const getUserStats = async (): Promise<UserStats> => {
  const allUsers = await getUsers({ limit: 20 });

  const stats: UserStats = {
    total_users: allUsers.length,
    verified_users: allUsers.filter((user) => user.verified).length,
    unverified_users: allUsers.filter((user) => !user.verified).length,
    recent_registrations: allUsers.filter((user) => {
      if (!user.created_at) return false;
      const createdDate = new Date(user.created_at);
      const thirtyDaysAgo = new Date();
      thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - 30);
      return createdDate > thirtyDaysAgo;
    }).length,
  };

  return stats;
};
