import { Resource } from "../resource.js";
import { diff } from "../util/diff.js";
import { CloudflareApiError } from "./api-error.js";
import { extractCloudflareResult } from "./api-response.js";
import { CloudflareApi, createCloudflareApi, } from "./api.js";
import { withJurisdiction } from "./bucket.js";
import { inferZoneIdFromPattern } from "./route.js";
const DEV_NOOP_ZONE = "noop-zone";
export const R2BucketCustomDomain = Resource("cloudflare::R2BucketCustomDomain", async function (_id, props) {
    if (this.scope.local && !props.dev?.remote && this.phase !== "delete") {
        return {
            domain: props.domain,
            enabled: props.enabled ?? false,
            zoneId: typeof props.zone === "string"
                ? props.zone
                : (props.zone?.id ?? DEV_NOOP_ZONE),
            ciphers: props.ciphers,
            minTLS: props.minTLS,
        };
    }
    const adopt = props.adopt ?? this.scope.adopt;
    const api = await createCloudflareApi(props);
    const payload = {
        domain: props.domain,
        enabled: props.enabled ?? true,
        zoneId: typeof props.zone === "string"
            ? props.zone
            : (props.zone?.id ??
                (await inferZoneIdFromPattern(api, props.domain))),
        ciphers: props.ciphers,
        minTLS: props.minTLS,
    };
    switch (this.phase) {
        case "create": {
            await createBucketCustomDomain(api, props.bucketName, props.jurisdiction, payload).catch(async (error) => {
                if (error instanceof CloudflareApiError &&
                    error.status === 409 &&
                    adopt) {
                    return await updateBucketCustomDomain(api, props.bucketName, props.jurisdiction, payload);
                }
                throw error;
            });
            return payload;
        }
        case "update": {
            if (this.output.zoneId !== DEV_NOOP_ZONE && // dev mode placeholder should not trigger replacement
                diff(this.output, payload).some((property) => property === "domain" || property === "zoneId")) {
                return this.replace();
            }
            await updateBucketCustomDomain(api, props.bucketName, props.jurisdiction, payload);
            return payload;
        }
        case "delete": {
            if (props.delete !== false) {
                await deleteBucketCustomDomain(api, props.bucketName, props.domain, props.jurisdiction);
            }
            return this.destroy();
        }
    }
});
async function createBucketCustomDomain(api, bucket, jurisdiction, payload) {
    return await extractCloudflareResult(`create custom domain for bucket "${bucket}"`, api.post(`/accounts/${api.accountId}/r2/buckets/${bucket}/domains/custom`, payload, { headers: withJurisdiction({ jurisdiction }) }));
}
async function updateBucketCustomDomain(api, bucket, jurisdiction, payload) {
    return await extractCloudflareResult(`update custom domain for bucket "${bucket}"`, api.put(`/accounts/${api.accountId}/r2/buckets/${bucket}/domains/custom/${encodeURIComponent(payload.domain)}`, payload, { headers: withJurisdiction({ jurisdiction }) }));
}
export async function deleteBucketCustomDomain(api, bucket, domain, jurisdiction) {
    return await extractCloudflareResult(`delete custom domain for bucket "${bucket}"`, api.delete(`/accounts/${api.accountId}/r2/buckets/${bucket}/domains/custom/${encodeURIComponent(domain)}`, { headers: withJurisdiction({ jurisdiction }) })).catch((error) => {
        if (!(error instanceof CloudflareApiError && error.status === 404)) {
            throw error;
        }
    });
}
export async function getBucketCustomDomain(api, bucket, domain, jurisdiction) {
    return await extractCloudflareResult(`get custom domain for bucket "${bucket}"`, api.get(`/accounts/${api.accountId}/r2/buckets/${bucket}/domains/custom/${encodeURIComponent(domain)}`, {
        headers: withJurisdiction({ jurisdiction }),
    })).catch((error) => {
        if (!(error instanceof CloudflareApiError && error.status === 404)) {
            throw error;
        }
    });
}
//# sourceMappingURL=bucket-custom-domain.js.map