export interface BackendAuthTokens {
  accessToken: string
  refreshToken: string
}

const BACKEND_BASE_URL_STORAGE_KEY = 'cmr.backend.baseUrl.v1'
const BACKEND_AUTH_TOKENS_STORAGE_KEY = 'cmr.backend.authTokens.v1'
const DEFAULT_BACKEND_BASE_URL = 'https://api.gotomars.xyz'
const LEGACY_LOCAL_BACKEND_BASE_URLS = [
  'http://127.0.0.1:8080',
  'https://127.0.0.1:8080',
  'http://localhost:8080',
  'https://localhost:8080',
]

function normalizeString(value: unknown): string {
  return typeof value === 'string' ? value.trim() : ''
}

export function normalizeBackendBaseUrl(value: unknown): string {
  const normalized = normalizeString(value).replace(/\/+$/, '')
  if (LEGACY_LOCAL_BACKEND_BASE_URLS.indexOf(normalized) >= 0) {
    return DEFAULT_BACKEND_BASE_URL
  }
  return normalized || DEFAULT_BACKEND_BASE_URL
}

export function loadBackendBaseUrl(): string {
  try {
    const stored = wx.getStorageSync(BACKEND_BASE_URL_STORAGE_KEY)
    const normalized = normalizeBackendBaseUrl(stored)
    if (normalized !== stored && normalized === DEFAULT_BACKEND_BASE_URL) {
      wx.setStorageSync(BACKEND_BASE_URL_STORAGE_KEY, normalized)
    }
    return normalized
  } catch {
    return DEFAULT_BACKEND_BASE_URL
  }
}

export function saveBackendBaseUrl(baseUrl: string): string {
  const normalized = normalizeBackendBaseUrl(baseUrl)
  try {
    wx.setStorageSync(BACKEND_BASE_URL_STORAGE_KEY, normalized)
  } catch {}
  return normalized
}

export function loadBackendAuthTokens(): BackendAuthTokens | null {
  try {
    const stored = wx.getStorageSync(BACKEND_AUTH_TOKENS_STORAGE_KEY)
    if (!stored || typeof stored !== 'object') {
      return null
    }

    const accessToken = normalizeString((stored as Record<string, unknown>).accessToken)
    const refreshToken = normalizeString((stored as Record<string, unknown>).refreshToken)
    if (!accessToken || !refreshToken) {
      return null
    }

    return {
      accessToken,
      refreshToken,
    }
  } catch {
    return null
  }
}

export function saveBackendAuthTokens(tokens: BackendAuthTokens): BackendAuthTokens {
  const normalized = {
    accessToken: normalizeString(tokens.accessToken),
    refreshToken: normalizeString(tokens.refreshToken),
  }
  try {
    wx.setStorageSync(BACKEND_AUTH_TOKENS_STORAGE_KEY, normalized)
  } catch {}
  return normalized
}

export function clearBackendAuthTokens() {
  try {
    wx.removeStorageSync(BACKEND_AUTH_TOKENS_STORAGE_KEY)
  } catch {}
}
