import {
  httpGetRequest,
  httpPostRequest,
  httpPutRequest,
  httpDeleteRequest,
  APIUrlGenerator,
} from "@/utils/baseHttpService";
import { API_ROUTES } from "@/constant/routes";
import {
  AdminUserInfo,
  CreateAdminUserRequest,
  UpdateAdminUserRequest,
  AdminUsersResponse,
  AdminUserResponse,
  CreateAdminUserResponse,
  UpdateAdminUserResponse,
  DeleteAdminUserResponse,
  AdminUserFilters,
} from "./_models";

export const getAdminUsers = async (filters?: AdminUserFilters) => {
  try {
    const queryParams: Record<string, string | number | null> = {};

    if (filters?.search) queryParams.search = filters.search;
    if (filters?.status) queryParams.status = filters.status;
    if (filters?.page) queryParams.page = filters.page;
    if (filters?.limit) queryParams.limit = filters.limit;

    const url = APIUrlGenerator(API_ROUTES.GET_ADMIN_USERS, queryParams);
    console.log("🔍 Admin Users URL:", url);
    console.log("🔍 API_ROUTES.GET_ADMIN_USERS:", API_ROUTES.GET_ADMIN_USERS);

    const response = await httpGetRequest<AdminUsersResponse>(url);

    console.log("Admin Users API Response:", response);
    console.log("Admin Users data:", response.data);

    // Handle different response structures
    if (response.data && (response.data as any).admin_users) {
      return Array.isArray((response.data as any).admin_users)
        ? (response.data as any).admin_users
        : [];
    }

    if (response.data && response.data.users) {
      return Array.isArray(response.data.users) ? response.data.users : [];
    }

    if (response.data && Array.isArray(response.data)) {
      return response.data;
    }

    return [];
  } catch (error) {
    console.error("Error fetching admin users:", error);
    return [];
  }
};

export const getAdminUser = async (id: string) => {
  try {
    const response = await httpGetRequest<AdminUserResponse>(
      APIUrlGenerator(API_ROUTES.GET_ADMIN_USER(id))
    );

    console.log("Get Admin User API Response:", response);
    console.log("Get Admin User data:", response.data);

    if (response.data && (response.data as any).admin_user) {
      return (response.data as any).admin_user;
    }

    if (response.data && response.data.user) {
      return response.data.user;
    }

    throw new Error("Failed to get admin user");
  } catch (error) {
    console.error("Error getting admin user:", error);
    throw error;
  }
};

export const createAdminUser = async (userData: CreateAdminUserRequest) => {
  try {
    console.log("🚀 Creating admin user with data:", userData);

    const response = await httpPostRequest<CreateAdminUserResponse>(
      APIUrlGenerator(API_ROUTES.CREATE_ADMIN_USER),
      userData
    );

    console.log("✅ Create Admin User API Response:", response);
    console.log("📊 Response data:", response.data);

    if (response.data && (response.data as any).admin_user) {
      console.log("✅ Returning admin_user from response");
      return (response.data as any).admin_user;
    }

    if (response.data && response.data.user) {
      console.log("✅ Returning user from response");
      return response.data.user;
    }

    console.log("⚠️ Response structure unexpected, throwing error");
    throw new Error("Failed to create admin user");
  } catch (error) {
    console.error("❌ Error creating admin user:", error);
    throw error;
  }
};

export const updateAdminUser = async (
  id: string,
  userData: UpdateAdminUserRequest
) => {
  try {
    const response = await httpPutRequest<UpdateAdminUserResponse>(
      APIUrlGenerator(API_ROUTES.UPDATE_ADMIN_USER(id)),
      userData
    );

    console.log("Update Admin User API Response:", response);
    console.log("Update Admin User data:", response.data);

    if (response.data && (response.data as any).admin_user) {
      return (response.data as any).admin_user;
    }

    if (response.data && response.data.user) {
      return response.data.user;
    }

    throw new Error("Failed to update admin user");
  } catch (error) {
    console.error("Error updating admin user:", error);
    throw error;
  }
};

export const deleteAdminUser = async (id: string) => {
  try {
    const response = await httpDeleteRequest<DeleteAdminUserResponse>(
      APIUrlGenerator(API_ROUTES.DELETE_ADMIN_USER(id))
    );

    return response.data;
  } catch (error) {
    console.error("Error deleting admin user:", error);
    throw error;
  }
};
