FROM golang:1.24-alpine

# Install required packages
RUN apk add --no-cache \
    ca-certificates \
    unzip \
    wget \
    gcc \
    musl-dev \
    protobuf-dev

# Install protoc-gen-go
RUN go install google.golang.org/protobuf/cmd/protoc-gen-go@latest
ENV PATH="$PATH:$(go env GOPATH)/bin"

# Working directory for the builder
WORKDIR /src

# Copy go files and download dependencies
COPY go.mod go.sum ./
RUN go mod download

# Download and compile protos
RUN mkdir -p protos models && \
    wget -qO- https://github.com/bjorge/hyttahub/archive/refs/tags/v0.1.53.tar.gz | \
    tar xz -C protos --strip-components=3 "hyttahub-0.1.53/lib/models" && \
    sed -i '/syntax = "proto3";/a option go_package = "pocketbase_emulator/models";' protos/*.proto && \
    protoc --proto_path=protos --go_out=models --go_opt=paths=source_relative protos/*.proto

# Copy the source code
COPY *.go ./
COPY migrations/ ./migrations/

# Run tests
RUN CGO_ENABLED=0 go test -v ./...

# Build custom PocketBase
RUN CGO_ENABLED=0 go build -o /usr/local/bin/pocketbase .

# Working directory for data and hooks
WORKDIR /app

# Create directories for persistent data
RUN mkdir -p /app/pb_data /app/pb_public

# Expose PocketBase ports
# 8090 = HTTP API + Admin UI
EXPOSE 8090

# Start PocketBase
# --dev enables the admin UI without HTTPS, --http binds to 0.0.0.0 so the
# host can reach it, --origins '*' allows all CORS origins for local dev.
CMD ["/usr/local/bin/pocketbase", "serve", \
     "--http=0.0.0.0:8090", \
     "--dir=/app/pb_data", \
     "--origins=*", \
     "--dev"]
