FROM node:20 AS builder
WORKDIR /app
COPY package*.json ./

# First generate package-lock.json if it doesn't exist, then do clean install
RUN if [ ! -f package-lock.json ]; then npm install --package-lock-only; fi && npm ci

COPY . .

# Vite bakes VITE_* values at build time, so compose must choose the env file
# during image build, not only at container runtime.
ARG ENV_FILE=.env
COPY ${ENV_FILE} .env

# Run build with production mode
RUN npm run build -- --mode production

FROM nginx:alpine
# Copy built files
COPY --from=builder /app/dist /usr/share/nginx/html

# .mjs files (pdfjs worker) must be served as application/javascript for module workers
RUN sed -i 's|application/javascript\s*js;|application/javascript js mjs;|' /etc/nginx/mime.types

# Create a simple nginx configuration
RUN echo 'server { \
    listen 3000; \
    root /usr/share/nginx/html; \
    index index.html; \
    location = /index.html { \
    expires -1; \
    add_header Cache-Control "no-store, no-cache, must-revalidate"; \
    } \
    location / { \
    try_files $uri $uri/ /index.html; \
    expires 30d; \
    add_header Cache-Control "public, no-transform"; \
    } \
    location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg|woff2?)$ { \
    expires 30d; \
    add_header Cache-Control "public, no-transform"; \
    } \
    location /searxng-api/ { \
    proxy_pass https://search.kevlarai.com/; \
    proxy_ssl_server_name on; \
    proxy_set_header Host search.kevlarai.com; \
    } \
    location ~ /\. { \
    deny all; \
    } \
    error_page 404 /index.html; \
    }' > /etc/nginx/conf.d/default.conf

# Set up permissions
RUN chown -R nginx:nginx /usr/share/nginx/html \
    && chown -R nginx:nginx /var/log/nginx

# Expose HTTP port (NPM will handle HTTPS)
EXPOSE 3000
