# Dockerfile para WhatsApp Bot Manager
# Multi-stage build para optimizar imagen final

# Stage 1: Builder
FROM php:8.2-fpm-alpine AS builder

# Instalar dependencias de compilación
RUN apk add --no-cache \
    $PHPIZE_DEPS \
    git \
    unzip \
    libzip \
    libzip-dev \
    icu \
    icu-dev \
    icu-libs \
    oniguruma-dev \
    freetype-dev \
    libjpeg-turbo-dev \
    libpng-dev \
    zlib-dev

# Instalar extensiones PHP necesarias
# Nota: curl viene incluido en la imagen base de PHP, solo necesitamos las libs del sistema
RUN apk add --no-cache curl-dev \
    && docker-php-ext-configure gd --with-freetype --with-jpeg \
    && docker-php-ext-install -j$(nproc) \
    pdo \
    pdo_mysql \
    mysqli \
    zip \
    intl \
    mbstring \
    gd \
    pcntl \
    opcache

# Instalar Redis extension (versión fija para cache reproducible)
RUN pecl install redis-6.0.2 && docker-php-ext-enable redis

# Instalar Composer
COPY --from=composer:2 /usr/bin/composer /usr/bin/composer

# Stage 2: Runner
FROM php:8.2-fpm-alpine

# Metadata
LABEL maintainer="U-Site.app"
LABEL description="WhatsApp Bot Manager with Queue Processing"
LABEL version="2.0"

# Configurar zona horaria Colombia
ENV TZ=America/Bogota

# Instalar dependencias runtime
RUN apk add --no-cache \
    bash \
    supervisor \
    nginx \
    curl \
    wget \
    libzip \
    icu \
    oniguruma \
    freetype \
    libjpeg-turbo \
    libpng \
    mysql-client \
    redis \
    ffmpeg \
    openssl \
    ca-certificates \
    tzdata \
    && cp /usr/share/zoneinfo/America/Bogota /etc/localtime \
    && echo "America/Bogota" > /etc/timezone \
    && update-ca-certificates \
    # Parche OpenSSL: deshabilitar session tickets TLS 1.3
    # Causa raíz del errno-56 'Connection reset by peer' con Meta/Facebook CDN
    && printf '\n[openssl_init]\nssl_conf = ssl_sect\n\n[ssl_sect]\nsystem_default = system_default_sect\n\n[system_default_sect]\nOptions = -SessionTicket\n' >> /etc/ssl/openssl.cnf

# Copiar extensiones PHP desde builder
COPY --from=builder /usr/local/lib/php/extensions/ /usr/local/lib/php/extensions/
COPY --from=builder /usr/local/etc/php/conf.d/ /usr/local/etc/php/conf.d/

# Copiar Composer desde builder
COPY --from=composer:2 /usr/bin/composer /usr/bin/composer

# Crear usuario para la aplicación y configurar grupos
RUN addgroup -g 1000 -S www && \
    adduser -u 1000 -S www -G www && \
    addgroup www nginx

# Configurar PHP
COPY docker/php/php.ini /usr/local/etc/php/conf.d/custom.ini
COPY docker/php/php-fpm.conf /usr/local/etc/php-fpm.d/www.conf

# Configurar Nginx
COPY docker/nginx/nginx.conf /etc/nginx/nginx.conf
COPY docker/nginx/default.conf /etc/nginx/http.d/default.conf

# Configurar Supervisor
COPY docker/supervisor/supervisord.conf /etc/supervisor/supervisord.conf
COPY docker/supervisor/programs.conf /etc/supervisor/conf.d/programs.conf

# Crear directorios necesarios
RUN mkdir -p \
    /var/www/html \
    /var/www/html/logs \
    /var/www/html/uploads \
    /var/log/supervisor \
    /run/php \
    /etc/nginx/ssl \
    && chown -R www:www /var/www/html \
    && chown -R www:www /var/log/supervisor

# Configurar working directory
WORKDIR /var/www/html

# Copiar código fuente
COPY --chown=www:www . .

# Instalar dependencias PHP (si composer.json existe)
RUN if [ -f composer.json ]; then \
    composer install --no-dev --optimize-autoloader --no-interaction; \
    fi

# Dar permisos a directorios críticos
RUN chmod -R 755 /var/www/html/logs \
    && chmod -R 755 /var/www/html/uploads \
    && chmod +x /var/www/html/worker.php \
    # Marcar instalación completa → activa modo producción en config.php
    # Crear ambas variantes: con y sin punto (distintas partes del código usan cada una)
    && touch /var/www/html/installation_completed \
    && touch /var/www/html/.installation_completed

# Health check
HEALTHCHECK --interval=30s --timeout=5s --start-period=30s --retries=3 \
    CMD curl -f http://localhost/health.php || exit 1

# Exponer puertos
EXPOSE 80

# Script de inicio
COPY docker/entrypoint.sh /usr/local/bin/entrypoint.sh
RUN chmod +x /usr/local/bin/entrypoint.sh

ENTRYPOINT ["/usr/local/bin/entrypoint.sh"]
CMD ["/usr/bin/supervisord", "-c", "/etc/supervisor/supervisord.conf"]
