
# syntax=docker/dockerfile:1

# =========================================================
# Base
# =========================================================
FROM node:20-bookworm-slim AS base

WORKDIR /app

ENV NEXT_TELEMETRY_DISABLED=1
ENV HUSKY=0


# =========================================================
# Dependencies
# =========================================================
FROM base AS deps

COPY package.json package-lock.json ./

RUN npm ci --no-audit --no-fund


# =========================================================
# Builder
# =========================================================
FROM base AS builder

ENV NODE_ENV=production
ENV BUILD_STANDALONE=true
ENV NEXT_TELEMETRY_DISABLED=1
ENV HUSKY=0

ARG NEXT_PUBLIC_SENTRY_DISABLED=true
ENV NEXT_PUBLIC_SENTRY_DISABLED=${NEXT_PUBLIC_SENTRY_DISABLED}

COPY --from=deps /app/node_modules ./node_modules
COPY . .

RUN npm run build


# =========================================================
# Migration / Seed image
#
# ใช้ target นี้สำหรับ:
# - npm run migrate
# - npm run seed:master-data
# - npm run seed:super-admin
# =========================================================
FROM base AS migrator

ENV NODE_ENV=production
ENV NEXT_TELEMETRY_DISABLED=1
ENV HUSKY=0

COPY --from=deps /app/node_modules ./node_modules
COPY package.json package-lock.json ./

# Drizzle configuration
COPY drizzle.config.* ./

# Migration files
COPY drizzle ./drizzle

# Database source code ที่ migration/seed scripts อาจ import
COPY src ./src
COPY scripts ./scripts

# ถ้าโปรเจกต์ใช้ tsconfig path alias
COPY tsconfig.json ./

# ถ้ามีไฟล์ config อื่นที่ scripts ใช้งาน ให้เปิดใช้ตามจริง
# COPY next.config.* ./
# COPY env.* ./

CMD ["npm", "run", "migrate"]


# =========================================================
# Production Runner
# =========================================================
FROM node:20-bookworm-slim AS runner

WORKDIR /app

ENV NODE_ENV=production
ENV NEXT_TELEMETRY_DISABLED=1
ENV PORT=3000
ENV HOSTNAME=0.0.0.0

RUN groupadd --system --gid 1001 nodejs \
    && useradd --system --uid 1001 --gid nodejs nextjs

COPY --from=builder --chown=nextjs:nodejs /app/public ./public
COPY --from=builder --chown=nextjs:nodejs /app/.next/standalone ./
COPY --from=builder --chown=nextjs:nodejs /app/.next/static ./.next/static

# กรณีแอปมี persistent local storage
RUN mkdir -p /app/storage \
    && chown -R nextjs:nodejs /app/storage

USER nextjs

EXPOSE 3000

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

