/**
 * Lightweight client for the Shortcut storage API.
 *
 * Wraps the storage endpoints used for file sync:
 * - POST /api/v1/storage/list
 * - POST /api/v1/storage/delete
 * - POST /api/v1/storage/write
 * - POST /api/v1/storage/signed-url
 * - Fetch signed URL (direct GCS download)
 */
import { SHORTCUT_API_URL } from '../../constants.js';
import { SHORTCUT_API_ENDPOINTS } from '../../endpoints.js';
function withStorageOwner(requestBody, options) {
    if (requestBody.storageContext === 'team' && options.teamId) {
        return { ...requestBody, teamId: options.teamId };
    }
    return requestBody;
}
// =============================================================================
// API calls
// =============================================================================
/** List files at a GCS path recursively. */
export async function storageList(accessToken, path, storageContext, options = {}) {
    const requestBody = withStorageOwner({ path, recursive: true, storageContext }, options);
    const response = await fetch(`${SHORTCUT_API_URL}${SHORTCUT_API_ENDPOINTS.storageList}`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            Authorization: `Bearer ${accessToken}`
        },
        body: JSON.stringify(requestBody)
    });
    if (!response.ok) {
        const body = await response.text().catch(() => '');
        throw new Error(`Storage list failed (${response.status}): ${body}`);
    }
    const data = (await response.json());
    return data.entries;
}
async function getSignedUrl(accessToken, path, storageContext, action, options = {}) {
    const requestBody = withStorageOwner({ path, action, storageContext }, options);
    const response = await fetch(`${SHORTCUT_API_URL}${SHORTCUT_API_ENDPOINTS.storageSignedUrl}`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            Authorization: `Bearer ${accessToken}`
        },
        body: JSON.stringify(requestBody)
    });
    if (!response.ok) {
        const body = await response.text().catch(() => '');
        throw new Error(`Signed URL failed (${response.status}): ${body}`);
    }
    const data = (await response.json());
    return data.signedUrl;
}
/** Download a file from GCS via signed URL. Returns raw bytes. */
export async function downloadFile(accessToken, path, storageContext, options = {}) {
    const signedUrl = await getSignedUrl(accessToken, path, storageContext, 'read', options);
    const response = await fetch(signedUrl);
    if (!response.ok) {
        throw new Error(`Download failed (${response.status})`);
    }
    return Buffer.from(await response.arrayBuffer());
}
/** Upload raw bytes to GCS via a signed write URL. */
export async function uploadFile(accessToken, path, storageContext, content) {
    const signedUrl = await getSignedUrl(accessToken, path, storageContext, 'write');
    const body = new Uint8Array(content);
    const response = await fetch(signedUrl, {
        method: 'PUT',
        headers: { 'Content-Type': 'application/octet-stream' },
        body
    });
    if (!response.ok) {
        throw new Error(`Upload failed (${response.status})`);
    }
}
/** Write UTF-8 text through the storage API. Skill manifests use this for provenance metadata. */
export async function storageWrite(accessToken, path, storageContext, content, contentType = 'text/plain; charset=utf-8', options = {}) {
    const requestBody = withStorageOwner({
        path,
        content: content.toString('utf-8'),
        contentType,
        storageContext
    }, options);
    const response = await fetch(`${SHORTCUT_API_URL}${SHORTCUT_API_ENDPOINTS.storageWrite}`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            Authorization: `Bearer ${accessToken}`
        },
        body: JSON.stringify(requestBody)
    });
    if (!response.ok) {
        const body = await response.text().catch(() => '');
        throw new Error(`Storage write failed (${response.status}): ${body}`);
    }
}
/** Delete a file or directory tree from storage. */
export async function storageDelete(accessToken, path, storageContext, recursive = false) {
    const response = await fetch(`${SHORTCUT_API_URL}${SHORTCUT_API_ENDPOINTS.storageDelete}`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            Authorization: `Bearer ${accessToken}`
        },
        body: JSON.stringify({ path, recursive, storageContext })
    });
    if (!response.ok) {
        const body = await response.text().catch(() => '');
        throw new Error(`Storage delete failed (${response.status}): ${body}`);
    }
    const data = (await response.json());
    return data.deleted;
}
//# sourceMappingURL=storage-client.js.map