FROM oven/bun:1 AS deps
WORKDIR /app

COPY package.json bun.lockb ./
COPY apps/backend/package.json apps/backend/
COPY apps/frontend/package.json apps/frontend/
COPY packages/common/package.json packages/common/

RUN bun install --frozen-lockfile --linker hoisted

FROM deps AS frontend-build
WORKDIR /app

COPY apps/frontend/ apps/frontend/
COPY packages/common/ packages/common/

RUN mkdir -p apps/backend && bun run --cwd apps/frontend build

FROM deps AS backend-build
WORKDIR /app

COPY apps/backend/ apps/backend/
COPY packages/common/ packages/common/

RUN bun run --cwd apps/backend prisma:generate

FROM oven/bun:1 AS production
WORKDIR /app

COPY --from=deps /app/package.json ./
COPY --from=deps /app/node_modules ./node_modules
COPY --from=backend-build /app/apps/backend ./apps/backend
COPY --from=backend-build /app/packages/common ./packages/common
COPY --from=frontend-build /app/apps/backend/web ./web

COPY apps/backend/docker-entrypoint.sh /usr/local/bin/
RUN chmod +x /usr/local/bin/docker-entrypoint.sh

EXPOSE 3000

ENTRYPOINT ["docker-entrypoint.sh"]
CMD ["bun", "run", "apps/backend/src/index.ts"]
