#!/bin/bash

# Laravel + Filament Deployment Script
# Usage: ./deploy.sh

set -e

echo "🚀 Starting deployment..."

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# Check if .env exists
if [ ! -f .env ]; then
    echo -e "${RED}❌ .env file not found!${NC}"
    echo "Please create .env file from .env.example"
    exit 1
fi

# Step 1: Install/Update Dependencies
echo -e "${YELLOW}📦 Installing PHP dependencies...${NC}"
composer install --no-dev --optimize-autoloader --no-interaction

echo -e "${YELLOW}📦 Installing Node dependencies...${NC}"
npm ci

# Step 2: Build Assets
echo -e "${YELLOW}🏗️  Building production assets...${NC}"
npm run build

# Step 3: Run Migrations
echo -e "${YELLOW}🗄️  Running database migrations...${NC}"
php artisan migrate --force

# Step 4: Clear and Cache
echo -e "${YELLOW}🧹 Clearing old caches...${NC}"
php artisan optimize:clear

echo -e "${YELLOW}⚡ Caching configuration...${NC}"
php artisan config:cache
php artisan route:cache
php artisan view:cache

# Step 5: Filament Specific
echo -e "${YELLOW}🎨 Optimizing Filament...${NC}"
php artisan filament:upgrade

# Step 6: Storage Link
echo -e "${YELLOW}🔗 Creating storage link...${NC}"
php artisan storage:link || true

# Step 7: Set Permissions
echo -e "${YELLOW}🔐 Setting permissions...${NC}"
chmod -R 775 storage bootstrap/cache
chown -R www-data:www-data storage bootstrap/cache 2>/dev/null || true

# Step 8: Optimize Autoloader
echo -e "${YELLOW}⚡ Optimizing autoloader...${NC}"
composer dump-autoload --optimize --classmap-authoritative

echo -e "${GREEN}✅ Deployment completed successfully!${NC}"
echo ""
echo "Next steps:"
echo "1. Verify .env configuration"
echo "2. Test admin login at /admin/login"
echo "3. Check application logs: tail -f storage/logs/laravel.log"

