import { Hono } from "hono";
import type { AppBindings } from "../../core/utils";
import { jsonError, parseDeviceId, toStatusCode } from "../../core/utils";
import {
    getDeviceById,
    handleContainerAction,
    listDevices,
} from "./service";

export const commandRouter = new Hono<AppBindings>()
    .get("/devices", async (c) => {
        const fctx = c.get("fctx");
        const result = await listDevices(fctx);

        if (result.isErr()) {
            const response = jsonError(result.error);
            return c.json(response.body, toStatusCode(response.status));
        }

        return c.json({ data: result.value, error: null });
    })
    .get("/devices/:id", async (c) => {
        const fctx = c.get("fctx");
        const parsedId = parseDeviceId(c.req.param("id"), fctx);

        if (typeof parsedId !== "number") {
            const response = jsonError(parsedId);
            return c.json(response.body, toStatusCode(response.status));
        }

        const result = await getDeviceById(fctx, parsedId);
        if (result.isErr()) {
            const response = jsonError(result.error);
            return c.json(response.body, toStatusCode(response.status));
        }

        return c.json({ data: result.value, error: null });
    })
    .post("/devices/:id/start", async (c) => {
        const fctx = c.get("fctx");
        const parsedId = parseDeviceId(c.req.param("id"), fctx);

        if (typeof parsedId !== "number") {
            const response = jsonError(parsedId);
            return c.json(response.body, toStatusCode(response.status));
        }

        const response = await handleContainerAction("start", parsedId, fctx);
        return c.json(response.body, toStatusCode(response.status));
    })
    .post("/devices/:id/stop", async (c) => {
        const fctx = c.get("fctx");
        const parsedId = parseDeviceId(c.req.param("id"), fctx);

        if (typeof parsedId !== "number") {
            const response = jsonError(parsedId);
            return c.json(response.body, toStatusCode(response.status));
        }

        const response = await handleContainerAction("stop", parsedId, fctx);
        return c.json(response.body, toStatusCode(response.status));
    })
    .post("/devices/:id/restart", async (c) => {
        const fctx = c.get("fctx");
        const parsedId = parseDeviceId(c.req.param("id"), fctx);

        if (typeof parsedId !== "number") {
            const response = jsonError(parsedId);
            return c.json(response.body, toStatusCode(response.status));
        }

        const response = await handleContainerAction("restart", parsedId, fctx);
        return c.json(response.body, toStatusCode(response.status));
    });
