import { CommonConfig } from "@website/common/config"
import { WebRpc, WebRpcSerializationDevelopment, WebRpcSerializationProduction } from "@website/common/webrpc"
import { Effect, Layer, Path } from "effect"
import { HttpMiddleware, HttpRouter, HttpServer, HttpStaticServer } from "effect/unstable/http"
import { RpcServer } from "effect/unstable/rpc"
import { WebRpcLive } from "./webrpc"


const WebRpcRoute = CommonConfig.webRpcHttpPath.pipe(
    Effect.map(path => RpcServer.layerHttp({
        group: WebRpc,
        path,
        protocol: "http",
    })),
    Layer.unwrap,
    Layer.provide(WebRpcLive),
)

const ProductionWebappRoute = Effect.gen(function*() {
    const path = yield* Path.Path
    const dist = path.join(yield* path.fromFileUrl(new URL(".", import.meta.resolve("@website/webapp"))), "dist")

    return HttpStaticServer.layer({
        root: dist,
        spa: true,
        cacheControl: "public, max-age=21600",
    })
}).pipe(
    Layer.unwrap
)


export const HttpAppDevelopment = WebRpcRoute.pipe(
    Layer.provide(WebRpcSerializationDevelopment),
    HttpRouter.toHttpEffect,
    Effect.map(app => HttpServer.withLogAddress(HttpServer.serve(
        HttpMiddleware.xForwardedHeaders(HttpMiddleware.logger(app)),
    ))),
    Layer.unwrap,
)

export const HttpAppProduction = Layer.mergeAll(
    WebRpcRoute.pipe(Layer.provide(WebRpcSerializationProduction)),
    ProductionWebappRoute,
).pipe(
    HttpRouter.toHttpEffect,
    Effect.map(app => HttpServer.withLogAddress(HttpServer.serve(
        HttpMiddleware.xForwardedHeaders(app),
    ))),
    Layer.unwrap,
)
