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

import { request } 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 request('/api/cloud/connections/webdav', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ provider, server_url: serverUrl, username, password }),
  })
}

export function updateDefaultStorage(backend) {
  return request('/api/users/me/default-storage', {
    method: 'PATCH',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ backend }),
  })
}

export function getCloudFolders(provider, folderId) {
  return request(`/api/cloud/folders/${provider}/${folderId}`)
}

/**
 * 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`)
}
