# Stage 1: Frontend build
FROM node:20-alpine AS frontend-build

WORKDIR /app

# Копируем только frontend-зависимости
COPY package*.json ./
RUN npm ci

# Копируем весь проект (vite.config.ts, src/, public/, и т.д.)
COPY . .

# Сборка фронтенда
RUN npm run build

# Stage 2: Backend build
FROM node:20-alpine AS backend-build

WORKDIR /app

COPY package*.json ./
RUN npm ci --only=production

# Копируем сервер
COPY server/ ./server/

# Stage 3: Final production image
FROM node:20-alpine AS production

WORKDIR /app

# Установка production-зависимостей
COPY package*.json ./
RUN npm ci --only=production && npm cache clean --force

# Копируем backend
COPY server/ ./server/

# Копируем собранный frontend
COPY --from=frontend-build /app/dist ./public

# Создаём каталог для загрузок
RUN mkdir -p uploads

# Создаём non-root user
RUN addgroup -g 1001 -S nodejs && adduser -S nodejs -u 1001
RUN chown -R nodejs:nodejs /app
USER nodejs

EXPOSE 3001

CMD ["node", "server/index.js"]
