import { NodeSdk } from "@effect/opentelemetry"
import { OTLPTraceExporter } from "@opentelemetry/exporter-trace-otlp-http"
import { BatchSpanProcessor } from "@opentelemetry/sdk-trace-base"
import { Effect, flow, Layer, Logger, Match } from "effect"
import { ServerConfig } from "./config"
import { HttpAppDevelopment, HttpAppProduction } from "./http"


const ServerDevelopment = Layer.empty.pipe(
    Layer.provideMerge(NodeSdk.layer(() => ({
        resource: { serviceName: "server" },
        spanProcessor: new BatchSpanProcessor(new OTLPTraceExporter({ url: "http://tempo:4318/v1/traces" }))
    }))),
    Layer.provideMerge(HttpAppDevelopment),
)

const ServerProduction = Layer.empty.pipe(
    Layer.provideMerge(HttpAppProduction),
)

export const Server = ServerConfig.mode.pipe(
    Effect.map(flow(
        Match.value,
        Match.when("development", () => ServerDevelopment),
        Match.when("production", () => ServerProduction),
        Match.exhaustive,
    )),

    Layer.unwrap,
    Layer.provideMerge(Logger.layer([Logger.consolePretty()])),
)
