import { Resource, ResourceKind } from "../resource.js";
import { handleApiError } from "./api-error.js";
import { createCloudflareApi, } from "./api.js";
export function isWarpDefaultProfile(resource) {
    return resource?.[ResourceKind] === "cloudflare::WarpDefaultProfile";
}
/**
 * Manages the Cloudflare WARP Default Device Profile, which defines the
 * account-wide default WARP client settings that apply when no custom profile matches.
 *
 * The default profile always exists and cannot be deleted. This resource allows you
 * to update its settings programmatically.
 *
 * @see https://developers.cloudflare.com/cloudflare-one/connections/connect-devices/warp/configure-warp/device-profiles/
 *
 * @example
 * ## Update default WARP settings
 *
 * Configure the default behavior for all devices
 *
 * const defaultProfile = await WarpDefaultProfile("default", {
 *   serviceModeV2: { mode: "warp" },
 *   autoConnect: 0,
 *   captivePortal: 180,
 *   supportUrl: "https://support.example.com"
 * });
 *
 * @example
 * ## Default profile with split tunnel
 *
 * Configure default split tunnel behavior for all devices
 *
 * const defaultWithSplitTunnel = await WarpDefaultProfile("default", {
 *   serviceModeV2: { mode: "warp" },
 *   splitTunnel: {
 *     mode: "exclude",
 *     entries: [
 *       { address: "10.0.0.0/8", description: "Internal network" },
 *       { address: "192.168.0.0/16", description: "Local network" }
 *     ]
 *   }
 * });
 *
 * @example
 * ## Locked default profile
 *
 * Create a locked-down default configuration
 *
 * const lockedDefault = await WarpDefaultProfile("default", {
 *   serviceModeV2: { mode: "warp" },
 *   switchLocked: true,
 *   allowedToLeave: false,
 *   disableAutoFallback: true,
 *   tunnelProtocol: "wireguard"
 * });
 */
export const WarpDefaultProfile = Resource("cloudflare::WarpDefaultProfile", async function (id, props = {}) {
    const api = await createCloudflareApi(props);
    if (this.phase === "delete") {
        // Default profile cannot be deleted, just remove from state
        return this.destroy();
    }
    // Update default profile (single PATCH endpoint)
    await updateDefaultPolicy(api, props);
    return {
        ...props,
        modifiedAt: Date.now(),
    };
});
// Type-safe mapping - TypeScript errors if any SimpleDeviceSettingKey is missing
const DEVICE_SETTINGS_MAP = {
    disableAutoFallback: "disable_auto_fallback",
    allowModeSwitch: "allow_mode_switch",
    switchLocked: "switch_locked",
    tunnelProtocol: "tunnel_protocol",
    autoConnect: "auto_connect",
    allowedToLeave: "allowed_to_leave",
    captivePortal: "captive_portal",
    supportUrl: "support_url",
    excludeOfficeIps: "exclude_office_ips",
    lanAllowMinutes: "lan_allow_minutes",
    lanAllowSubnetSize: "lan_allow_subnet_size",
};
async function updateDefaultPolicy(api, props) {
    // Build device settings object
    const deviceSettings = {};
    if (props.serviceModeV2) {
        deviceSettings.service_mode_v2 = {
            mode: props.serviceModeV2.mode,
            ...(props.serviceModeV2.port && { port: props.serviceModeV2.port }),
        };
    }
    // Apply all simple field mappings
    for (const propKey of Object.keys(DEVICE_SETTINGS_MAP)) {
        deviceSettings[DEVICE_SETTINGS_MAP[propKey]] = props[propKey];
    }
    // Split tunnel config is part of the body for default policy
    if (props.splitTunnel) {
        if (props.splitTunnel.mode === "include") {
            deviceSettings.include = props.splitTunnel.entries.map((entry) => ({
                address: entry.address,
                ...(entry.description && { description: entry.description }),
            }));
        }
        else {
            deviceSettings.exclude = props.splitTunnel.entries.map((entry) => ({
                address: entry.address,
                ...(entry.description && { description: entry.description }),
            }));
        }
    }
    const requestBody = {
        ...(Object.keys(deviceSettings).length > 0 && { ...deviceSettings }),
    };
    const response = await api.patch(`/accounts/${api.accountId}/devices/policy`, requestBody);
    if (!response.ok) {
        await handleApiError(response, "update", "warp_default_profile", "default");
    }
}
async function updateDefaultSplitTunnel(api, config) {
    const routes = config.entries.map((entry) => ({
        address: entry.address,
        ...(entry.description && { description: entry.description }),
    }));
    if (config.mode === "include") {
        const response = await api.put(`/accounts/${api.accountId}/devices/policies/default/includes`, routes);
        if (!response.ok) {
            await handleApiError(response, "update split tunnel includes", "warp_default_profile", "default");
        }
    }
    else {
        const response = await api.put(`/accounts/${api.accountId}/devices/policies/default/excludes`, routes);
        if (!response.ok) {
            await handleApiError(response, "update split tunnel excludes", "warp_default_profile", "default");
        }
    }
}
//# sourceMappingURL=warp-default-profile.js.map