# Use the official Bun image
FROM oven/bun:1 as base
WORKDIR /usr/src/app

# Install dependencies into temp directory
# This will cache them and speed up future builds
FROM base AS install
RUN mkdir -p /temp/dev
COPY package.json bun.lock /temp/dev/
RUN cd /temp/dev && bun install --frozen-lockfile

# Install with --production (exclude devDependencies)
RUN mkdir -p /temp/prod
COPY package.json bun.lock /temp/prod/
RUN cd /temp/prod && bun install --frozen-lockfile --production

# Copy node_modules from temp directory
# Then copy all (non-ignored) project files into the image
FROM base AS prerelease
COPY --from=install /temp/dev/node_modules node_modules
COPY . .

# [Optional] Tests & Build
ENV NODE_ENV=production
# RUN bun test
# RUN bun run build

# Final stage for app image
FROM base AS release
COPY --from=install /temp/prod/node_modules node_modules
COPY --from=prerelease /usr/src/app/src src
COPY --from=prerelease /usr/src/app/package.json .
COPY --from=prerelease /usr/src/app/bun.lock .
COPY --from=prerelease /usr/src/app/tsconfig.json .
COPY --from=prerelease /usr/src/app/tailwind.config.js .
COPY --from=prerelease /usr/src/app/postcss.config.js .

# Ensure the DB directory/file exists or is volume mounted
# We will handle the DB via volume in docker-compose
# Copy the seed script so we can run it if needed
COPY --from=prerelease /usr/src/app/src/db/seed.ts src/db/seed.ts
COPY --from=prerelease /usr/src/app/src/db/schema.ts src/db/schema.ts

# Expose port
EXPOSE 3000/tcp

# Start the server
ENTRYPOINT [ "bun", "run", "src/index.tsx" ]
