import { getDeviceController } from "@pkg/logic/domains/device/controller";
import type { FlowExecCtx } from "@pkg/logic/core/flow.execution.context";
import type { Device } from "@pkg/logic/domains/device/data";
import { createAppError, jsonError } from "../../core/utils";
import { AndroidCommandExecutor } from "./executor";
import { logDomainEvent } from "@pkg/logger";
import { ERROR_CODES } from "@pkg/result";

export type InternalAction = "start" | "stop" | "restart";

const deviceController = getDeviceController();
const adbBinary = process.env.ADB_BIN || "adb";
const adbTimeoutMs = Number(process.env.ADB_TIMEOUT_MS || "15000");

const androidExecutor = new AndroidCommandExecutor(adbBinary, adbTimeoutMs);

export async function handleContainerAction(
    action: InternalAction,
    deviceId: number,
    fctx: FlowExecCtx,
) {
    const deviceResult = await deviceController.getById(fctx, deviceId);
    if (deviceResult.isErr()) {
        return jsonError(deviceResult.error);
    }

    logDomainEvent({
        level: "warn",
        event: "orchestrator.device_container.stubbed",
        fctx,
        meta: {
            action,
            deviceId,
            containerId: deviceResult.value.containerId,
        },
    });

    return jsonError(
        createAppError(
            fctx,
            ERROR_CODES.NOT_IMPLEMENTED,
            "Container action not implemented",
            "This container control endpoint is currently a stub",
            `action=${action} deviceId=${deviceId}`,
        ),
        501,
    );
}

export async function listDevices(fctx: FlowExecCtx) {
    return deviceController.list(fctx);
}

export async function getDeviceById(fctx: FlowExecCtx, deviceId: number) {
    return deviceController.getById(fctx, deviceId);
}

export async function prepareAssignedApp(device: Device, packageName: string) {
    return androidExecutor.prepareAssignedApp(device, packageName);
}

export async function disconnectDevice(device: Device) {
    return androidExecutor.disconnect(device);
}
