# Stage 1: Build frontend
FROM node:20-alpine AS builder

WORKDIR /build

ARG VITE_API_URL=/api

COPY package*.json ./
RUN npm install

COPY . .
RUN VITE_API_URL=$VITE_API_URL npm run build

# Stage 2: Production environment with Node.js, Nginx, and MongoDB Community Edition (ARM64 & AMD64 native support via Ubuntu 22.04)
FROM ubuntu:22.04

WORKDIR /app

# Prevent interactive prompts during apt install
ENV DEBIAN_FRONTEND=noninteractive

# Install dependencies needed for Node.js, MongoDB repo, and general setup
RUN apt-get update && apt-get install -y \
    gnupg \
    curl \
    ca-certificates \
    nginx \
    procps \
    && curl -fsSL https://deb.nodesource.com/setup_20.x | bash - \
    && apt-get install -y nodejs \
    && rm -rf /var/lib/apt/lists/*

# Add MongoDB official GPG key and repository (MongoDB 8.0 for Ubuntu 22.04 Jammy - supports arm64 and amd64 natively)
RUN curl -fsSL https://www.mongodb.org/static/pgp/server-8.0.asc | \
    gpg --dearmor -o /usr/share/keyrings/mongodb-server-8.0.gpg \
    && echo "deb [ signed-by=/usr/share/keyrings/mongodb-server-8.0.gpg ] http://repo.mongodb.org/apt/ubuntu jammy/mongodb-org/8.0 multiverse" | \
    tee /etc/apt/sources.list.d/mongodb-org-8.0.list

# Install MongoDB Community Edition
RUN apt-get update && apt-get install -y \
    mongodb-org \
    && rm -rf /var/lib/apt/lists/*

# Copy built frontend to nginx html folder
COPY --from=builder /build/dist /usr/share/nginx/html

# Copy server files
COPY server/package*.json ./server/
RUN cd ./server && npm install --omit=dev

COPY server/ ./server/

# Configure Nginx for Debian
RUN rm -f /etc/nginx/sites-enabled/default
COPY nginx.conf /etc/nginx/conf.d/default.conf

# Create MongoDB data and run directories with correct permissions
RUN mkdir -p /data/db /var/log/mongodb /var/run/mongodb && \
    chown -R mongodb:mongodb /data/db /var/log/mongodb /var/run/mongodb

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

# ONLY expose port 80 (HTTP)
EXPOSE 80

ENV DB_NAME=hospital
ENV ADMIN_DNI=35242633
ENV ADMIN_PASSWORD=admin123

ENTRYPOINT ["/docker-entrypoint.sh"]
