#!/bin/bash

# Script: laravel_setup.sh
# Description: This script automates Laravel setup tasks.

# Check if Laravel Sail script exists in the vendor directory
if [ ! -f "./vendor/bin/sail" ]; then
  echo "ERROR: Laravel Sail script not found. Make sure you've run 'composer install'."
  exit 1
fi

# Define a shell function for Sail
function sail {
  ./vendor/bin/sail "$@"
}

# Function to run a Laravel artisan command and display a result message
function run_laravel_command {
  command="$1"
  description="$2"
  sail artisan "$command"
  if [ $? -eq 0 ]; then
    echo "✔️ $description completed successfully."
  else
    echo "❌ $description failed."
    exit 1
  fi
}

# Function to run Composer install inside Laravel Sail
function run_composer_install {
  description="$1"
  sail composer install
  if [ $? -eq 0 ]; then
    echo "✔️ $description completed successfully."
  else
    echo "❌ $description failed."
    exit 1
  fi
}

# Function to run npm install with prefixes inside Laravel Sail
function run_npm_install {
  description="$1"
  prefix="$2"
  sail npm install --prefix="$prefix"
  if [ $? -eq 0 ]; then
    echo "✔️ $description completed successfully."
  else
    echo "❌ $description failed."
    exit 1
  fi
}

# Display a message indicating the start of Laravel commands
echo "🚀 Starting Laravel commands..."

# Clear the config
run_laravel_command "config:clear" "Clearing the config"

# Clear the cache by tags
run_laravel_command "cache:clear" "Clearing the cache"

# Clear the application cache by tags
run_laravel_command "cache:app-clear" "Clearing the application cache"

# Run migrations
run_laravel_command "migrate" "Run migrations"

# Seed the database with default data
run_laravel_command "db:seed" "Seeding the database with default data"

# Import translations
run_laravel_command "trans:import" "Importing translations"

# Clear the application routes
run_laravel_command "route:clear" "Clearing the application routes"

# Clear the translated routes
run_laravel_command "route:trans:clear" "Clearing the translated routes"

# Clear the cache by tags
run_laravel_command "cache:clear" "Clearing the cache"

# Clear the application cache by tags
run_laravel_command "cache:app-clear" "Clearing the application cache"

# Install Composer inside Laravel Sail
run_composer_install "Installing Composer"

# Run npm install with prefixes inside Laravel Sail
run_npm_install "Running 'npm install' with prefix=resources/shop" "resources/shop"

# Run npm install with prefixes inside Laravel Sail
run_npm_install "Running 'npm install' with prefix=resources/admin" "resources/admin"

# Display a message indicating the end of Laravel commands
echo "✅ Laravel commands completed successfully."