import axios from 'axios';
import { salla } from '../config';

let accessToken = salla.accessToken || null;
let refreshToken = salla.refreshToken || null;

export function getAuthStatus() {
  return { connected: !!accessToken, hasRefreshToken: !!refreshToken };
}

export function setTokens(access: string, refresh?: string) {
  accessToken = access;
  if (refresh) refreshToken = refresh;
}

export async function refreshAccessToken(): Promise<string> {
  if (!refreshToken) throw new Error('No refresh token available');

  const response = await axios.post('https://accounts.salla.sa/oauth2/token', {
    client_id: salla.clientId,
    client_secret: salla.clientSecret,
    grant_type: 'refresh_token',
    refresh_token: refreshToken,
  });

  accessToken = response.data.access_token;
  if (response.data.refresh_token) {
    refreshToken = response.data.refresh_token;
  }

  return accessToken!;
}

export async function callSallaAPI(
  endpoint: string,
  method: 'GET' | 'POST' = 'GET',
  data: unknown = null
): Promise<unknown> {
  if (!accessToken) throw new Error('Not authenticated. Visit /auth/login first.');

  try {
    const response = await axios({
      method,
      url: `https://api.salla.dev/admin/v2${endpoint}`,
      headers: {
        Authorization: `Bearer ${accessToken}`,
        'Content-Type': 'application/json',
      },
      data,
    });
    return response.data;
  } catch (err: unknown) {
    const axiosErr = err as { response?: { status: number } };
    if (axiosErr.response?.status === 401) {
      await refreshAccessToken();
      return callSallaAPI(endpoint, method, data);
    }
    throw err;
  }
}
