# ========================================
# 第一阶段：构建前端资源
# ========================================
FROM node:20-alpine AS frontend-builder

# 设置工作目录
WORKDIR /app

# 安装 bun
RUN npm install -g bun@latest

# 复制 package.json 并配置 npm 镜像
COPY package.json ./
RUN npm config set registry https://registry.npmmirror.com

# 安装依赖并生成 lockfile
RUN bun install

# 复制其他配置文件
COPY tailwind.config.js postcss.config.js vite.config.js ./

# 复制源码
COPY resources/ ./resources/

# 构建前端资源
RUN bun run build

# ========================================
# 第二阶段：PHP 运行时
# ========================================
FROM php:8.3-cli-alpine AS runtime

# 安装系统依赖 - 使用阿里云镜像
RUN sed -i 's/dl-cdn.alpinelinux.org/mirrors.aliyun.com/g' /etc/apk/repositories && \
    apk add --no-cache \
        git \
        curl \
        ca-certificates \
        libzip-dev \
        libpng-dev \
        oniguruma-dev \
        libjpeg-turbo-dev \
        freetype-dev \
        icu-dev \
        libzip-dev \
        sqlite-dev \
        && rm -rf /var/cache/apk/*

# 安装 PHP 扩展
RUN docker-php-ext-configure gd --with-freetype --with-jpeg && \
    docker-php-ext-install -j$(nproc) pdo pdo_mysql pdo_sqlite gd zip intl

# 安装 Composer - 使用国内镜像
COPY --from=composer:2 /usr/bin/composer /usr/bin/composer
RUN composer config -g repo.packagist composer https://mirrors.aliyun.com/composer/

# 创建应用目录
WORKDIR /app

# 复制 Composer 文件并安装依赖
COPY composer.json composer.lock ./
RUN composer install --no-dev --no-interaction --prefer-dist --optimize-autoloader --no-scripts

# 复制应用代码（排除 node_modules, vendor 等）
COPY . .

# 从第一阶段复制构建好的前端资源
COPY --from=frontend-builder /app/public/build ./public/build

# 缓存 Laravel 配置和路由
RUN php artisan config:cache && \
    php artisan route:cache && \
    php artisan view:cache && \
    php artisan filament:upgrade || true

# 创建必要目录
RUN mkdir -p storage/logs storage/framework/cache storage/framework/sessions storage/framework/views bootstrap/cache

# 设置权限
RUN chown -R www-data:www-data /app && \
    chmod -R 755 /app && \
    chmod -R 777 /app/storage /app/bootstrap/cache

EXPOSE 8000

# 健康检查
HEALTHCHECK --interval=30s --timeout=3s --start-period=5s --retries=3 \
    CMD php artisan --version || exit 1

CMD ["php", "artisan", "serve", "--host=0.0.0.0", "--port=8000"]
