# Build Stage
FROM node:20-alpine AS builder
WORKDIR /app

# Install dependencies
COPY package*.json ./
COPY prisma ./prisma/
RUN npm install

# Build the application
COPY . .
# Use a temporary DB for generation
ENV DATABASE_URL="file:./temp.db"

RUN npx prisma generate
RUN npm run build

# Production Stage
FROM node:20-alpine AS runner
WORKDIR /app

# Set production environment
ENV NODE_ENV=production
ENV PORT=3000
# Force absolute path in production
ENV DATABASE_URL="file:/app/data/dev.db"

# Install production dependencies only
COPY package*.json ./
RUN npm install --omit=dev

# Copy build artifacts and necessary files
COPY --from=builder /app/.next ./.next
COPY --from=builder /app/public ./public
COPY --from=builder /app/next.config.mjs ./
COPY --from=builder /app/prisma ./prisma
# Copy dictionaries since they are needed at runtime
COPY --from=builder /app/dictionaries ./dictionaries
COPY --from=builder /app/node_modules/.prisma ./node_modules/.prisma
COPY --from=builder /app/node_modules/@prisma ./node_modules/@prisma

# Ensure data directory exists
RUN mkdir -p /app/data

# Script to run migrations and start the app
RUN printf "#!/bin/sh\n\
    set -e\n\
    echo \"Starting initialization...\"\n\
    echo \"Database URL: \$DATABASE_URL\"\n\
    echo \"Running migrations...\"\n\
    # Use npx prisma migrate deploy with explicit schema path to be safe\n\
    npx prisma migrate deploy --schema ./prisma/schema.prisma\n\
    echo \"Starting application...\"\n\
    npm start" > /app/start.sh

RUN chmod +x /app/start.sh

EXPOSE 3000

CMD ["sh", "/app/start.sh"]
