#!/bin/bash

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

PROJECT_ROOT="/www/wwwroot/chat.ay.lc" # <--- 确认这里的路径是否正确

echo -e "${BLUE}========================================${NC}"
echo -e "${BLUE}  🚀 Laravel 稳健更新脚本 (带严格检查) ${NC}"
echo -e "${BLUE}========================================${NC}"

cd "$PROJECT_ROOT" || { echo -e "${RED}❌ 无法进入项目目录：$PROJECT_ROOT${NC}"; exit 1; }

# 1. Git Pull（先重置 lock 文件，避免服务器环境差异导致冲突）
echo -e "${YELLOW}[1/7] 拉取代码...${NC}"
git checkout -- composer.lock package-lock.json 2>/dev/null || true
git fetch origin && git pull origin master
if [ $? -ne 0 ]; then echo -e "${RED}❌ Git 失败${NC}"; exit 1; fi

# 2. Composer Install (关键检查点)
echo -e "${YELLOW}[2/7] 安装依赖 (Composer)...${NC}"
composer install --no-dev --optimize-autoloader --classmap-authoritative --no-interaction
COMPOSER_EXIT_CODE=$?

if [ $COMPOSER_EXIT_CODE -ne 0 ]; then
    echo -e "${RED}========================================${NC}"
    echo -e "${RED}  ❌ 致命错误：Composer 安装失败！ ${NC}"
    echo -e "${RED}  vendor/autoload.php 未生成，网站将不可用。 ${NC}"
    echo -e "${RED}  请检查上方的错误日志 (网络？内存？PHP版本？) ${NC}"
    echo -e "${RED}========================================${NC}"
    exit 1
fi

# 检查文件是否真的存在
if [ ! -f "vendor/autoload.php" ]; then
    echo -e "${RED}❌ 奇怪：Composer 显示成功，但 vendor/autoload.php 不存在！${NC}"
    exit 1
fi
echo -e "${GREEN}✅ 依赖安装成功且文件存在。${NC}"

# 3. 前端构建
echo -e "${YELLOW}[3/7] 前端构建 (npm run build)...${NC}"
npm run build
if [ $? -ne 0 ]; then echo -e "${RED}❌ npm run build 失败${NC}"; exit 1; fi
echo -e "${GREEN}✅ 前端资源构建完成。${NC}"

# 3. 清理缓存
echo -e "${YELLOW}[4/7] 清理缓存...${NC}"
php artisan config:clear && php artisan cache:clear && php artisan view:clear

# 4. 数据库迁移
echo -e "${YELLOW}[5/7] 数据库迁移...${NC}"
php artisan migrate --force

# 5. 优化
echo -e "${YELLOW}[6/7] 生产环境优化...${NC}"
php artisan config:cache && php artisan route:cache && php artisan view:cache

# 6. 权限
echo -e "${YELLOW}[7/7] 修复权限...${NC}"
chmod -R 755 app assets public storage bootstrap database vendor routes config resources 

echo -e "${GREEN}========================================${NC}"
echo -e "${GREEN}  🎉 更新成功！网站已恢复。 ${NC}"
echo -e "${GREEN}========================================${NC}"