FROM golang:1.24-alpine AS build
RUN apk add --no-cache git ca-certificates protobuf-dev
WORKDIR /app

ARG PROTOC_GEN_GO_VERSION=v1.36.10
ARG PROTOC_GEN_GO_GRPC_VERSION=v1.5.1

# use repo-level go.mod so modules are resolvable (build.context must be repo root)
COPY go.mod go.sum ./
RUN go mod download

# install Go protoc plugins (pinned for Go 1.24 compatibility)
RUN go install google.golang.org/protobuf/cmd/protoc-gen-go@${PROTOC_GEN_GO_VERSION} && \
    go install google.golang.org/grpc/cmd/protoc-gen-go-grpc@${PROTOC_GEN_GO_GRPC_VERSION}

# copy service sources and proto files into the image
COPY services/auth-service ./services/auth-service
COPY proto ./proto

# generate proto files
RUN mkdir -p proto/auth proto/user proto/post && \
    export PATH=/go/bin:$PATH && \
    protoc --go_out=proto --go_opt=paths=source_relative \
           --go-grpc_out=proto --go-grpc_opt=paths=source_relative \
           --proto_path=proto \
           proto/auth.proto proto/user.proto proto/post.proto && \
    ls -la proto/auth/ proto/user/ proto/post/

# build a static binary for the auth service
RUN CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -o /usr/local/bin/auth-service ./services/auth-service/cmd

FROM alpine:3.20
RUN apk add --no-cache ca-certificates
COPY --from=build /usr/local/bin/auth-service /usr/local/bin/auth-service
EXPOSE 50051
ENTRYPOINT ["/usr/local/bin/auth-service"]
