FROM golang:1.21-alpine AS builder

WORKDIR /workspace

# Copy go mod files
COPY go.mod go.mod
COPY go.sum go.sum

# Download dependencies and update go.sum
RUN go mod download && go mod tidy

# Install controller-gen for code generation (compatible with Go 1.21)
RUN go install sigs.k8s.io/controller-tools/cmd/controller-gen@v0.13.0

# Copy source code
COPY . .

# Generate code (DeepCopy methods)
RUN controller-gen object:headerFile="hack/boilerplate.go.txt" paths="./apis/v1alpha1/..."

# Fix generated code - Spec/Status types don't have DeepCopyInto, so use value assignment
RUN if [ -f "apis/v1alpha1/zz_generated.deepcopy.go" ]; then \
    sed -i.bak \
        -e 's/in\.Spec\.DeepCopyInto(&out\.Spec)/out.Spec = in.Spec/g' \
        -e 's/in\.Status\.DeepCopyInto(&out\.Status)/out.Status = in.Status/g' \
        -e 's/in\.Spec\.DeepCopyInto(out\.Spec)/out.Spec = in.Spec/g' \
        -e 's/in\.Status\.DeepCopyInto(out\.Status)/out.Status = in.Status/g' \
        apis/v1alpha1/zz_generated.deepcopy.go && \
    rm -f apis/v1alpha1/zz_generated.deepcopy.go.bak; \
    fi

# Build
RUN CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build -a -o provider ./cmd/provider

FROM alpine:latest

RUN apk --no-cache add ca-certificates

WORKDIR /root/

COPY --from=builder /workspace/provider .

ENTRYPOINT ["./provider"]

