# syntax=docker/dockerfile:1.7

# =============================================================================
# Stage 1: Install frontend dependencies
# =============================================================================
FROM oven/bun:1.3.11 AS deps-frontend
WORKDIR /app
COPY package.json bun.lock ./
COPY apps/frontend/package.json apps/frontend/
COPY packages/api-contract/package.json packages/api-contract/
RUN bun install

# =============================================================================
# Stage 2: Build Frontend
# =============================================================================
FROM deps-frontend AS build-frontend
WORKDIR /app
COPY apps/frontend ./apps/frontend
COPY packages ./packages
ARG VITE_API_BASE_URL
ENV VITE_API_BASE_URL=${VITE_API_BASE_URL}
RUN bun run build:frontend

# =============================================================================
# Stage 3: Install backend dependencies
# =============================================================================
FROM oven/bun:1.3.11 AS deps-backend
WORKDIR /app
COPY package.json bun.lock ./
COPY apps/backend/package.json apps/backend/
COPY packages/api-contract/package.json packages/api-contract/
RUN bun install

# =============================================================================
# Stage 4: Prisma Generate
# =============================================================================
FROM deps-backend AS prisma
WORKDIR /app
ARG DATABASE_URL
ENV DATABASE_URL=${DATABASE_URL}
COPY apps/backend ./apps/backend
RUN bun --cwd apps/backend prisma:generate

# =============================================================================
# Stage 5: Build Backend
# =============================================================================
FROM prisma AS build-backend
WORKDIR /app
COPY packages ./packages
RUN bun --cwd apps/backend build

# =============================================================================
# Stage 6: Runner - Production image
# =============================================================================
FROM oven/bun:1.3.11 AS runner
WORKDIR /app
ENV NODE_ENV=production HOST=0.0.0.0 PORT=3000

COPY --from=build-backend /app/node_modules ./node_modules
COPY --from=build-frontend /app/apps/frontend/dist ./apps/backend/public
COPY --from=build-backend /app/apps/backend ./apps/backend
COPY --from=build-backend /app/packages ./packages
COPY package.json ./
COPY entrypoint.sh /app/entrypoint.sh

RUN chmod +x /app/entrypoint.sh

EXPOSE 3000
CMD ["/app/entrypoint.sh"]
