# FROM node:14 as frontend
# WORKDIR /app
# COPY . /app
# RUN npm install --production
# RUN npm run build

# FROM node:14 as backend
# WORKDIR /app
# COPY /backend /app
# RUN npm install

# FROM node:14
# WORKDIR /app
# COPY --from=backend /app /app/
# COPY --from=frontend /app/build /app/build

# EXPOSE 8080

# CMD ["npm", "run", "start"]


const express = require('express');
const cors = require('cors');
const path = require('path');
const cookieParser = require('cookie-parser');
const mongoose = require('mongoose');
require('dotenv').config();
const { sessionMiddleware } = require('./config/session');

const PORT = process.env.PORT || 5000;

const app = express();

app.use(cookieParser());
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
app.set('trust proxy', 1);

/* ---------- CORS ---------- */
app.use(
    cors({
        origin:
            process.env.NODE_ENV === 'production'
                ? true               // same origin (Docker / prod)
                : 'http://localhost:3000',
        credentials: true,
    })
);

app.use(sessionMiddleware);

const server = app.listen(PORT, "0.0.0.0", () => {
    console.log(`Server listening on port ${PORT}`);
});

/* ---------- Mongo + Socket ---------- */
require('./config/database')(mongoose);
require('./config/socket')(server);

/* ---------- Serve React build ---------- */
if (process.env.NODE_ENV === 'production') {
    const buildPath = path.resolve(__dirname, 'build');

    app.use(express.static(buildPath));

    app.get('*', (req, res) => {
        res.sendFile(path.join(buildPath, 'index.html'));
    });
}

module.exports = { server };
root@DietPi:~/mern-ludo/backend# ^C
root@DietPi:~/mern-ludo/backend# cd .
root@DietPi:~/mern-ludo/backend# cd ..
root@DietPi:~/mern-ludo# nano Dockerfile
root@DietPi:~/mern-ludo# cat Dockerfile
# Node 20 for Pi 5 (ARM64)
FROM node:20-bullseye-slim

WORKDIR /app

# Copy all files
COPY . /app

# Install frontend (root) dependencies
RUN npm install --legacy-peer-deps

# Build frontend
RUN npm run build

# Install backend dependencies
RUN cd backend && npm install --production --legacy-peer-deps

# Move frontend build into backend/public for Express
# RUN cp -r build backend/public
RUN rm -rf backend/build
RUN cp -r build backend/build

# Copy wait-for-mongo.sh and make it executable
COPY wait-for-mongo.sh ./
RUN chmod +x wait-for-mongo.sh

# Default fallback values (can be overridden by Compose)
ENV NODE_ENV=production
ENV PORT=8080
ENV CONNECTION_URI=mongodb://mongo:27017/ludo?replicaSet=rs0

EXPOSE 18081

# Start backend with wait-for-mongo
CMD ["bash", "./wait-for-mongo.sh", "mongo", "27017", "node", "backend/server.js"]
