import { getSupportedAppController } from "@pkg/logic/domains/supported-app/controller";
import {
    createSupportedAppSchema,
    updateSupportedAppSchema,
} from "@pkg/logic/domains/supported-app/data";
import { getFlowExecCtxForRemoteFuncs, unauthorized } from "$lib/core/server.utils";
import { command, getRequestEvent, query } from "$app/server";
import * as v from "valibot";

const sac = getSupportedAppController();

export const listSupportedAppsSQ = query(async () => {
    const event = getRequestEvent();
    const fctx = await getFlowExecCtxForRemoteFuncs(event.locals);
    if (!fctx.userId) return unauthorized(fctx);

    const res = await sac.list(fctx);
    return res.isOk()
        ? { data: res.value, error: null }
        : { data: null, error: res.error };
});

export const createSupportedAppSC = command(
    createSupportedAppSchema,
    async (payload) => {
        const event = getRequestEvent();
        const fctx = await getFlowExecCtxForRemoteFuncs(event.locals);
        if (!fctx.userId) return unauthorized(fctx);

        const res = await sac.create(fctx, payload);
        return res.isOk()
            ? { data: res.value, error: null }
            : { data: null, error: res.error };
    },
);

export const updateSupportedAppSC = command(
    v.object({ id: v.number(), data: updateSupportedAppSchema }),
    async (payload) => {
        const event = getRequestEvent();
        const fctx = await getFlowExecCtxForRemoteFuncs(event.locals);
        if (!fctx.userId) return unauthorized(fctx);

        const res = await sac.update(fctx, payload.id, payload.data);
        return res.isOk()
            ? { data: res.value, error: null }
            : { data: null, error: res.error };
    },
);

export const deleteSupportedAppSC = command(
    v.object({ id: v.number() }),
    async (payload) => {
        const event = getRequestEvent();
        const fctx = await getFlowExecCtxForRemoteFuncs(event.locals);
        if (!fctx.userId) return unauthorized(fctx);

        const res = await sac.delete(fctx, payload.id);
        return res.isOk()
            ? { data: res.value, error: null }
            : { data: null, error: res.error };
    },
);
