# Use Node.js 20 Alpine for smaller image size
FROM node:20-alpine AS base

# Install system dependencies
RUN apk add --no-cache \
    libc6-compat \
    openssl \
    sqlite \
    wget \
    dumb-init

# Set working directory
WORKDIR /app

# Install dependencies only when needed
FROM base AS deps
# Copy package files
COPY package.json package-lock.json* ./
RUN npm ci --only=production --frozen-lockfile && npm cache clean --force

# Rebuild the source code only when needed
FROM base AS builder
# Copy package files
COPY package.json package-lock.json* ./
RUN npm ci --frozen-lockfile

# Copy source code
COPY . .

# Generate Prisma client
RUN npx prisma generate

# Build the application
RUN npm run build

# Production image, copy all the files and run the app
FROM base AS runner

# Create a non-root user
RUN addgroup --system --gid 1001 nodejs && \
    adduser --system --uid 1001 remix

# Copy built application
COPY --from=builder --chown=remix:nodejs /app/build ./build
COPY --from=builder --chown=remix:nodejs /app/public ./public
COPY --from=builder --chown=remix:nodejs /app/package.json ./package.json
COPY --from=builder --chown=remix:nodejs /app/prisma ./prisma
COPY --from=builder --chown=remix:nodejs /app/scripts ./scripts

# Copy production dependencies
COPY --from=deps --chown=remix:nodejs /app/node_modules ./node_modules

# Create necessary directories
RUN mkdir -p /app/data /app/logs && \
    chown -R remix:nodejs /app/data /app/logs

# Create startup script
COPY --chown=remix:nodejs <<EOF /app/start.sh
#!/bin/sh
set -e

echo "Starting Phosphat Report Application..."

# Run database migrations
echo "Running database migrations..."
npx prisma db push --accept-data-loss

# Run seed using production script
echo "Seeding database..."
if [ -f "scripts/seed-production.js" ]; then
    echo "Using production seed script..."
    node scripts/seed-production.js
else
    echo "Production seed script not found, trying alternative methods..."
    if [ -f "prisma/seed.js" ]; then
        echo "Using JavaScript seed file..."
        node prisma/seed.js
    else
        echo "No seeding method available, skipping..."
    fi
fi

echo "Database setup complete. Starting application on port 3000..."
export PORT=3000
exec npx remix-serve ./build/server/index.js
EOF

RUN chmod +x /app/start.sh

USER remix

EXPOSE 3000

ENV NODE_ENV=production
ENV PORT=3000

# Health check with wget (more reliable than node)
HEALTHCHECK --interval=30s --timeout=10s --start-period=40s --retries=3 \
    CMD wget --no-verbose --tries=1 --spider http://localhost:3000/health || exit 1

# Use dumb-init to handle signals properly
ENTRYPOINT ["dumb-init", "--"]
CMD ["/app/start.sh"]