function getApiBase(): string {
  return process.env.NEXT_PUBLIC_API_URL || 'https://deployhub-back.workzy.co';
}

const API_URL = getApiBase();

export class ApiError extends Error {
  constructor(public status: number, message: string) {
    super(message);
    this.name = 'ApiError';
  }
}

async function fetchApi(endpoint: string, options?: RequestInit) {
  const token = localStorage.getItem('admin_token');
  const headers: Record<string, string> = {
    'Content-Type': 'application/json',
  };

  if (token) {
    headers['Authorization'] = `Bearer ${token}`;
  }

  const response = await fetch(`${API_URL}${endpoint}`, {
    ...options,
    headers,
  });

  if (!response.ok) {
    const error = await response.json().catch(() => ({ message: 'Request failed' }));
    throw new ApiError(response.status, error.message || `HTTP ${response.status}`);
  }

  return response.json();
}

export const api = {
  auth: {
    login: async (email: string, password: string) => {
      const response = await fetchApi('/api/admin/auth/login', {
        method: 'POST',
        body: JSON.stringify({ email, password }),
      });
      localStorage.setItem('admin_token', response.token);
      localStorage.setItem('admin_email', email);
      return response;
    },
    logout: () => {
      localStorage.removeItem('admin_token');
      localStorage.removeItem('admin_email');
    },
    getToken: () => {
      return localStorage.getItem('admin_token');
    },
    getEmail: () => {
      return localStorage.getItem('admin_email');
    },
  },

  admin: {
    getStats: () => fetchApi('/api/admin/stats'),
    getUsers: (page = 1, limit = 20, search?: string) => {
      const params = new URLSearchParams({ page: String(page), limit: String(limit) });
      if (search) params.append('search', search);
      return fetchApi(`/api/admin/users?${params}`);
    },
    getUserDetails: (userId: string) => fetchApi(`/api/admin/users/${userId}`),
    updateUserStatus: (userId: string, isActive: boolean) =>
      fetchApi(`/api/admin/users/${userId}/status`, {
        method: 'PATCH',
        body: JSON.stringify({ isActive }),
      }),
    updateUserRole: (userId: string, role: string) =>
      fetchApi(`/api/admin/users/${userId}/role`, {
        method: 'PATCH',
        body: JSON.stringify({ role }),
      }),
    deleteUser: (userId: string) =>
      fetchApi(`/api/admin/users/${userId}`, { method: 'DELETE' }),
    getRecentBuilds: (limit = 10) =>
      fetchApi(`/api/admin/recent-builds?limit=${limit}`),
    getRecentUsers: (limit = 10) =>
      fetchApi(`/api/admin/recent-users?limit=${limit}`),
    getAppsWithIcons: (limit = 50) =>
      fetchApi(`/api/admin/apps-with-icons?limit=${limit}`),
    getAllBuilds: (page = 1, limit = 20, search?: string) => {
      const params = new URLSearchParams({ page: String(page), limit: String(limit) });
      if (search) params.append('search', search);
      return fetchApi(`/api/admin/builds?${params}`);
    },
    getActiveUsers: (page = 1, limit = 20) =>
      fetchApi(`/api/admin/active-users?page=${page}&limit=${limit}`),
    getUniqueApps: (page = 1, limit = 20, search?: string) => {
      const params = new URLSearchParams({ page: String(page), limit: String(limit) });
      if (search) params.append('search', search);
      return fetchApi(`/api/admin/unique-apps?${params}`);
    },
    updateUserSettings: (userId: string, updates: { buildLinkExpiryDays?: number | null; aiReleaseNotesEnabled?: boolean | null; maxBuildSizeMb?: number | null; cicdEnabled?: boolean | null; slackEnabled?: boolean | null }) =>
      fetchApi(`/api/admin/users/${userId}/settings`, {
        method: 'PATCH',
        body: JSON.stringify(updates),
      }),
    getSettings: () => fetchApi('/api/admin/settings'),
    updateSettings: (updates: { buildLinkExpiryDays?: number; aiReleaseNotesEnabled?: boolean; maxBuildSizeMb?: number; cicdEnabled?: boolean; slackEnabled?: boolean }) =>
      fetchApi('/api/admin/settings', {
        method: 'PATCH',
        body: JSON.stringify(updates),
      }),
  },

  drive: {
    getIconUrl: (fileId: string) => `${API_URL}/api/drive/icon/${fileId}`,
  },
};

function getFrontendBase(): string {
  return process.env.NEXT_PUBLIC_FRONTEND_URL || 'https://deployhub.workzy.co';
}

export const getDownloadPageUrl = (buildId: string) =>
  `${getFrontendBase()}/download?build_id=${encodeURIComponent(buildId)}`;

export const getShortUrl = (shortCode: string) =>
  `${getFrontendBase()}/s/${shortCode}`;
