import { CommonConfig } from "@website/common/config"
import { WebRpc, WebRpcSerializationDevelopment, WebRpcSerializationProduction } from "@website/common/webrpc"
import { Duration, Effect, FileSystem, Layer, Path } from "effect"
import { HttpMiddleware, HttpRouter, HttpServer, HttpServerRequest, HttpServerResponse } 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 = HttpRouter.add("*", "*", Effect.gen(function*() {
    const path = yield* Path.Path
    const fs = yield* FileSystem.FileSystem
    const request = yield* HttpServerRequest.HttpServerRequest
    const dist = path.join(yield* path.fromFileUrl(new URL(".", import.meta.resolve("@website/webapp"))), "dist")
    const source = path.join(dist, decodeURI(new URL(request.url, "http://localhost").pathname))
    const exists = yield* fs.stat(source).pipe(
        Effect.map(stat => stat.type === "File"),
        Effect.catch(() => Effect.succeed(false)),
    )

    return yield* HttpServerResponse.file(exists ? source : path.join(dist, "index.html")).pipe(
        Effect.map(HttpServerResponse.setHeader(
            "Cache-Control",
            `public, max-age=${Duration.toSeconds("6 hours")}, immutable`,
        )),
    )
}))


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,
)
