# Build context: repo root (docker build -f infra/backend.Dockerfile .)
#
# Local test:  docker build -f infra/backend.Dockerfile -t nexuscrm-backend .
# AWS deploy:  docker build --platform linux/amd64 -f infra/backend.Dockerfile -t nexuscrm-backend .

FROM --platform=$BUILDPLATFORM golang:1.24-alpine AS builder

ARG TARGETPLATFORM
ARG TARGETOS=linux
ARG TARGETARCH

RUN apk add --no-cache git ca-certificates

WORKDIR /src

# Copy dependency files first for layer caching
COPY shared/go.mod shared/go.sum ./shared/
COPY backend/go.mod backend/go.sum ./backend/

WORKDIR /src/backend
RUN go mod download

# Copy source
WORKDIR /src
COPY shared/ ./shared/
COPY backend/ ./backend/

# Build static binaries for the target platform
WORKDIR /src/backend
RUN CGO_ENABLED=0 GOOS=${TARGETOS} GOARCH=${TARGETARCH} go build -ldflags="-s -w" -o /nexuscrm-server ./cmd/server/
RUN CGO_ENABLED=0 GOOS=${TARGETOS} GOARCH=${TARGETARCH} go build -ldflags="-s -w" -o /nexuscrm-setup ./cmd/setup/

# -----------------------------------------------------------
FROM alpine:3.20

RUN apk add --no-cache ca-certificates tzdata \
    && addgroup -S app && adduser -S app -G app

COPY --from=builder /nexuscrm-server /usr/local/bin/nexuscrm-server
COPY --from=builder /nexuscrm-setup /usr/local/bin/nexuscrm-setup
COPY infra/entrypoint.sh /usr/local/bin/entrypoint.sh

USER app
EXPOSE 3001

ENTRYPOINT ["/usr/local/bin/entrypoint.sh"]
