#!/bin/bash

# POS ATP - Auto Installation Script
# This script installs both backend (Laravel) and frontend (Angular)

set -e

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

echo -e "${BLUE}==================================================${NC}"
echo -e "${BLUE}        POS ATP - INSTALLATION PROJECT            ${NC}"
echo -e "${BLUE}==================================================${NC}"

# 1. Check Requirements
echo -e "\n${BLUE}[1/5] Checking requirements...${NC}"

if ! [ -x "$(command -v php)" ]; then
  echo -e "${RED}Error: php is not installed.${NC}" >&2
  exit 1
fi

if ! [ -x "$(command -v composer)" ]; then
  echo -e "${RED}Error: composer is not installed.${NC}" >&2
  exit 1
fi

if ! [ -x "$(command -v npm)" ]; then
  echo -e "${RED}Error: npm is not installed.${NC}" >&2
  exit 1
fi

echo -e "${GREEN}Requirements met.${NC}"

# 2. Setup Backend
echo -e "\n${BLUE}[2/5] Setting up Backend (Laravel)...${NC}"
cd backend

if [ ! -f .env ]; then
    echo -e "${BLUE}Copying .env.example to .env...${NC}"
    cp .env.example .env
    echo -e "${RED}IMPORTANT: Please update .env with your database credentials!${NC}"
    # Pause for user to edit if interactive
    read -p "Press enter after you have configured your database in backend/.env to continue..."
fi

echo -e "Installing composer dependencies..."
composer install --no-dev --optimize-autoloader

echo -e "Generating app key..."
php artisan key:generate --force

echo -e "Running migrations and seeders..."
# We use --force because it's usually on production-like environment
php artisan migrate --force
php artisan db:seed --force

echo -e "Creating storage link..."
php artisan storage:link || true

echo -e "Setting permissions..."
chmod -R 775 storage bootstrap/cache
chown -R www-data:www-data storage bootstrap/cache || true

cd ..

# 3. Setup Frontend
echo -e "\n${BLUE}[3/5] Setting up Frontend (Angular)...${NC}"
cd frontend

# Ask for API URL
echo -e "${BLUE}Configuring Frontend API...${NC}"
DEFAULT_API_URL="http://localhost:8000/api/v1"
read -p "Enter your Backend API URL (default: $DEFAULT_API_URL): " API_URL
API_URL=${API_URL:-$DEFAULT_API_URL}

# Update API_URL in app.constants.ts
CONSTANTS_FILE="src/app/core/constants/app.constants.ts"
if [ -f "$CONSTANTS_FILE" ]; then
    echo -e "Updating $CONSTANTS_FILE with $API_URL..."
    # Use sed to replace the line. We use | as delimiter to avoid issues with / in URL
    sed -i "s|export const API_URL = '.*';|export const API_URL = '$API_URL';|" "$CONSTANTS_FILE" || \
    sed -i "" "s|export const API_URL = '.*';|export const API_URL = '$API_URL';|" "$CONSTANTS_FILE" # Mac version
fi

echo -e "Installing npm dependencies..."
npm install

echo -e "Building frontend..."
npm run build

cd ..

# 4. Queue Service Setup
echo -e "\n${BLUE}[4/5] Setting up Queue Workers...${NC}"
echo -e "Note: For production, please use Supervisor to manage queue workers."
echo -e "Instructions for Supervisor will be saved to supervisor-recipe.txt"

cat > supervisor-recipe.txt <<EOF
[program:pos-atp-worker]
process_name=%(program_name)s_%(process_num)02d
command=php $(pwd)/backend/artisan queue:work --sleep=3 --tries=3 --max-time=3600
autostart=true
autorestart=true
stopasgroup=true
killasgroup=true
user=$(whoami)
numprocs=2
redirect_stderr=true
stdout_logfile=$(pwd)/backend/storage/logs/worker.log
stopwaitsecs=3600
EOF

echo -e "Starting a temporary queue worker in background for initial jobs..."
cd backend
php artisan queue:work --once || true
cd ..

# 5. Optimization
echo -e "\n${BLUE}[5/5] Optimizing application...${NC}"
cd backend
php artisan config:cache
php artisan route:cache
php artisan view:cache
php artisan event:cache
cd ..

# 5. Finished
echo -e "\n${BLUE}==================================================${NC}"
echo -e "${GREEN}           INSTALLATION COMPLETED!                ${NC}"
echo -e "${BLUE}==================================================${NC}"
echo -e "Your application is ready."
echo -e "Backend: Run 'php artisan serve' or configure web server to 'backend/public'"
echo -e "Frontend: Build files are in 'frontend/dist/frontend'"
echo -e "Admin Login: admin@posatp.com / admin@123"
echo -e "${BLUE}==================================================${NC}"
