# Stage 1: Builder
FROM oven/bun:1 AS builder

WORKDIR /app

# Copy package files
COPY package.json bun.lock ./
COPY prisma ./prisma

# Install dependencies (including devDependencies for build tools)
RUN bun install --frozen-lockfile

# Generate Prisma Client
RUN bun prisma generate

# Copy source code
COPY . .

# Build frontend
# We use asset-naming to ensure the CSS file is named index.css so we can overwrite it with Tailwind
RUN bun build ./src/ui/index.html --outdir ./dist --asset-naming="[name].[ext]"

# Build Tailwind CSS
# We overwrite the CSS generated by bun build with the one processed by Tailwind
RUN bunx tailwindcss -i ./src/ui/index.css -o ./dist/index.css --minify

# Stage 2: Runner
FROM oven/bun:1-alpine AS runner

WORKDIR /app

# Copy dependencies and build artifacts
COPY --from=builder /app/node_modules ./node_modules
COPY --from=builder /app/src ./src
COPY --from=builder /app/dist ./dist
COPY --from=builder /app/package.json ./package.json
COPY --from=builder /app/prisma ./prisma
COPY --from=builder /app/bunfig.toml ./bunfig.toml
COPY --from=builder /app/public ./public
COPY --from=builder /app/prisma.config.ts ./prisma.config.ts
COPY --from=builder /app/example-data ./example-data

# Create data directory
RUN mkdir -p data

# Expose port
EXPOSE 3000

# Set environment to production
ENV NODE_ENV=production

# Run migrations and start server
CMD ["sh", "-c", "bun prisma migrate deploy && bun src/index.ts"]
