/**
 * Cloud Storage API — connections, OAuth initiation, folder browsing, config.
 *
 * Consumers: stores/cloudConnections.js, SettingsCloudTab.vue,
 *            CloudCredentialModal.vue, CloudProviderTreeItem.vue,
 *            CloudFolderTreeItem.vue
 */

import { request, jsonRequest } from './utils.js'

export function listCloudConnections() {
  return request('/api/cloud/connections')
}

export function disconnectCloud(id) {
  return request(`/api/cloud/connections/${id}`, { method: 'DELETE' })
}

export function connectWebDav(provider, serverUrl, username, password) {
  return jsonRequest('/api/cloud/connections/webdav', 'POST', {
    provider,
    server_url: serverUrl,
    username,
    password,
  })
}

export function updateDefaultStorage(backend) {
  return jsonRequest('/api/users/me/default-storage', 'PATCH', { backend })
}

/**
 * Browse a cloud folder by connection UUID and optional parent_ref.
 * connectionId is always a UUID; parentRef is a provider path string (default '').
 */
export function getCloudFoldersByConnectionId(connectionId, parentRef = '') {
  const qs = parentRef ? `?parent_ref=${encodeURIComponent(parentRef)}` : ''
  return request(`/api/cloud/connections/${connectionId}/items${qs}`)
}

/** @deprecated Use getCloudFoldersByConnectionId instead. */
export function getCloudFolders(provider, folderId) {
  return request(`/api/cloud/folders/${provider}/${folderId}`)
}

/**
 * Rename a cloud connection's display name.
 */
export function renameCloudConnection(id, displayName) {
  return jsonRequest(`/api/cloud/connections/${id}`, 'PATCH', { display_name: displayName })
}

/**
 * Initiate OAuth flow for Google Drive or OneDrive.
 *
 * Returns a JSON object {url: "<authorization_url>"} from the backend.
 * The caller is responsible for navigating: window.location.href = data.url
 *
 * Using request() (not bare window.location.href) ensures the Bearer header
 * is injected and the 401→refresh retry path fires if the token has expired.
 * See plan 05-10 trust boundary: frontend→/api/cloud/oauth/initiate/{provider}.
 */
export function initiateOAuth(provider) {
  return request(`/api/cloud/oauth/initiate/${provider}`)
}

/**
 * Fetch non-secret configuration for a WebDAV/Nextcloud connection (edit flow).
 *
 * Returns {id, provider, server_url, connection_username} — never the password.
 * Used to pre-populate the Edit modal when re-editing an existing connection.
 */
export function getConnectionConfig(connectionId) {
  return request(`/api/cloud/connections/${connectionId}/config`)
}

/**
 * Update credentials for an existing WebDAV/Nextcloud connection (owner-scoped).
 *
 * Only fields included are changed. Omitting password preserves the existing secret.
 * Backend re-validates the URL and runs a health-check before committing.
 */
export function updateWebDavCredentials(connectionId, { serverUrl, username, password }) {
  const body = {}
  if (serverUrl !== undefined) body.server_url = serverUrl
  if (username !== undefined) body.username = username
  if (password !== undefined && password !== '') body.password = password
  return jsonRequest(`/api/cloud/connections/${connectionId}/credentials`, 'PUT', body)
}
