import { ERROR_CODES, type Err } from "@pkg/result";

export function normalizeBaseUrl(url: string): string {
    return url.endsWith("/") ? url.slice(0, -1) : url;
}

export function createLinkFlowError(
    flowId: string,
    code: string,
    message: string,
    description: string,
    detail: string,
    actionable?: boolean,
): Err {
    return {
        flowId,
        code,
        message,
        description,
        detail,
        actionable,
    };
}

export function isErrPayload(value: unknown): value is Err {
    return !!value && typeof value === "object" && "code" in value;
}

export function missingDeviceError(flowId: string, token: string): Err {
    return createLinkFlowError(
        flowId,
        ERROR_CODES.NOT_ALLOWED,
        "Link is not assigned to a device",
        "This link cannot start a session because no device is assigned",
        `token=${token}`,
        true,
    );
}

export function missingSupportedAppError(flowId: string, token: string): Err {
    return createLinkFlowError(
        flowId,
        ERROR_CODES.NOT_ALLOWED,
        "Link is not assigned to an app",
        "This link cannot start a session because no app is assigned",
        `token=${token}`,
        true,
    );
}

export function unavailableDeviceError(
    flowId: string,
    device: { id: number; status: string; inUse: boolean },
): Err {
    return createLinkFlowError(
        flowId,
        ERROR_CODES.NOT_ALLOWED,
        "Device is not available",
        "The assigned device is currently busy or offline",
        `deviceId=${device.id} status=${device.status} inUse=${device.inUse}`,
        true,
    );
}
