FROM node:22-alpine AS frontend-builder

WORKDIR /app/frontend

RUN corepack enable && corepack prepare pnpm@latest --activate

COPY frontend/package.json frontend/pnpm-lock.yaml ./

RUN pnpm install --frozen-lockfile

COPY frontend/ ./

ENV NODE_OPTIONS="--max-old-space-size=2048"
RUN pnpm vite build

FROM golang:1.21-alpine AS backend-builder

WORKDIR /app

RUN apk add --no-cache git

COPY backend/go.mod backend/go.sum ./

RUN go mod download

COPY backend/ ./

RUN mkdir -p cmd/embedded/dist

COPY --from=frontend-builder /app/frontend/dist ./cmd/embedded/dist/

RUN CGO_ENABLED=0 GOOS=linux go build -a -installsuffix cgo -o main ./cmd/main.go

FROM alpine:latest

RUN apk --no-cache add ca-certificates tzdata su-exec mailcap

RUN addgroup -g 1001 -S appgroup && \
    adduser -u 1001 -S appuser -G appgroup

WORKDIR /app

COPY --from=backend-builder /app/main .
COPY docker-entrypoint.sh /usr/local/bin/

RUN chmod +x /usr/local/bin/docker-entrypoint.sh && \
    mkdir -p /app/data /app/uploads && \
    chown -R appuser:appgroup /app

EXPOSE 8080

ENTRYPOINT ["docker-entrypoint.sh"]
CMD ["./main"]
