# syntax=docker/dockerfile:1

# ------------------------------------------------------------------------------
# Stage 1: Install frontend dependencies
# ------------------------------------------------------------------------------
FROM node:lts-trixie-slim AS deps
WORKDIR /app/frontend

COPY frontend/package.json frontend/package-lock.json* ./
RUN npm ci

# ------------------------------------------------------------------------------
# Stage 2: Build the TanStack Start frontend
# ------------------------------------------------------------------------------
FROM node:lts-trixie-slim AS builder
WORKDIR /app/frontend

COPY --from=deps /app/frontend/node_modules ./node_modules
COPY frontend/ ./

ENV NODE_ENV=production
RUN npm run build

# ------------------------------------------------------------------------------
# Stage 3: Fetch PocketBase binary for target architecture
# ------------------------------------------------------------------------------
FROM alpine:3.20 AS pb-downloader
ARG TARGETARCH=amd64
ARG PB_VERSION=0.40.2

RUN apk add --no-cache curl unzip ca-certificates \
  && PB_ARCH="${TARGETARCH}" \
  && if [ "$TARGETARCH" = "x86_64" ]; then PB_ARCH="amd64"; fi \
  && if [ "$TARGETARCH" = "aarch64" ]; then PB_ARCH="arm64"; fi \
  && curl -fsSL -o /tmp/pb.zip "https://github.com/pocketbase/pocketbase/releases/download/v${PB_VERSION}/pocketbase_${PB_VERSION}_linux_${PB_ARCH}.zip" \
  && unzip /tmp/pb.zip -d /app \
  && chmod +x /app/pocketbase \
  && rm -f /tmp/pb.zip

# ------------------------------------------------------------------------------
# Stage 4: Production runner
# ------------------------------------------------------------------------------
FROM node:lts-trixie-slim AS runner
LABEL maintainer="Amritanshu <docker@tanshu.com>"

RUN apt-get update && apt-get install -y --no-install-recommends \
    curl \
    ca-certificates \
  && rm -rf /var/lib/apt/lists/*

WORKDIR /app

# Copy PocketBase binary and migrations
COPY --from=pb-downloader /app/pocketbase /app/pocketbase
COPY backend/pb_migrations /app/pb_migrations

# Copy compiled frontend application
COPY --from=builder /app/frontend/.output /app/frontend/.output

# Copy entrypoint script
COPY docker-entrypoint.sh /app/docker-entrypoint.sh
RUN chmod +x /app/docker-entrypoint.sh

# Environment variables
ENV NODE_ENV=production
ENV PORT=3000
ENV HOST=0.0.0.0
ENV PB_DATA_DIR=/app/pb_data

# Persistent data volume for PocketBase SQLite database and file storage
VOLUME ["/app/pb_data"]

# Port 3000: TanStack Start Web Application
# Port 8090: PocketBase REST API & Admin UI
EXPOSE 3000 8090

ENTRYPOINT ["/app/docker-entrypoint.sh"]
