#!/usr/bin/env bash

CONTAINER_NAME="eloboost24-webapp"

function docker_exec() {
    local as_user
    as_user=$(id -u):$(id -g)
    local interactive=""
    local cmd=""

    while (( "$#" )); do
        case "$1" in
            --as-root)
                as_user="root"
                shift
                ;;
            --interactive)
                if [ -t 0 ]; then
                    interactive="-it"
                else
                    interactive="-i"
                fi
                shift
                ;;
            --non-interactive)
                interactive=""
                shift
                ;;
            *)
                cmd=("$@")
                break
                ;;
        esac
    done

    docker exec -u "$as_user" $interactive $CONTAINER_NAME "${cmd[@]}" || return 1
}

function check_docker() {
    if ! docker info > /dev/null 2>&1; then
      echo "Docker is not running. Aborting."
      return 1
    fi
}

function check_container() {
    if ! docker ps | grep -q $CONTAINER_NAME; then
        return 1
    fi
}

function start_container() {
    if [ -t 0 ]; then
        read -p "Docker containers not running. Do you wish to start them? [Yn]" -n 1 -r reply
        echo
        reply=${reply:-Y}
    else
        echo "Docker containers not running. Starting automatically (non-interactive mode)."
        reply="Y"
    fi

    if [[ $reply =~ ^[Yy]$ ]]; then
        if [ -f docker-compose.yml ]; then
            docker compose up -d || return 1
        else
            echo "No docker-compose.yml in current directory. Aborting."
            return 1
        fi
    else
        return 1
    fi
}

function ensure_user() {
    if [[ $(docker_exec id -u worker) -ne $(id -u) ]]; then
        docker_exec --as-root usermod -u "$(id -u)" worker || return 1

        if [[ $OSTYPE != "darwin"* ]]; then
          docker_exec --as-root groupmod -g "$(id -g)" worker || return 1
        fi
    fi

    if [[ $OSTYPE != "darwin"* ]]; then
      docker_exec --as-root chown -R "$(id -u):$(id -g)" .
    fi
}


function exec_commands() {
    case "$1" in
    "init")
        docker_exec composer install
        docker_exec php artisan key:generate
        docker_exec php artisan storage:link
        docker_exec php artisan migrate:fresh --seed
        docker_exec php artisan route:trans:cache
        docker_exec pnpm install
        exec_commands routes-generate
        exec_commands translations-generate
        docker_exec pnpm run build

        if [[ $OSTYPE == "darwin"* ]]; then
          echo "Please restart docker containers"
        fi
        ;;
    "fix")
        docker_exec php vendor/bin/php-cs-fixer fix --show-progress=dots
        ;;
    "format")
        docker_exec pnpm run format
        ;;
    "check")
        docker_exec pnpm run check
        ;;
    "test")
        docker_exec --interactive php artisan test
        ;;
    "tests-ai")
        shift
        docker_exec --interactive php artisan test --testsuite=AiIntegration "$@"
        ;;
    "routes-generate")
        docker_exec php artisan ziggy:generate resources/assets/js/ziggy.js --types
        ;;
    "translations-generate")
        docker_exec php artisan lang:js --json resources/svelte/lib/constant/lang.json
        ;;
    "vs-code-exec")
        docker_exec php "${2/\/workspaces\/Eloboost24/\/app}"
        ;;
    "typesense-flush")
        docker_exec php artisan scout:flush App\\Post
        docker_exec php artisan scout:flush App\\User
        docker_exec php artisan scout:flush App\\ZippyProfile
        docker_exec php artisan scout:flush App\\ZippyProduct
        docker_exec php artisan scout:flush App\\ZippyProductOffer
        docker_exec php artisan scout:flush App\\Offer
        docker_exec php artisan scout:flush App\\Marketplace\\Model\\MarketplaceItem
        ;;
    "typesense-import")
        docker_exec php artisan scout:import App\\Post --fresh
        docker_exec php artisan scout:import App\\User --fresh
        docker_exec php artisan scout:import App\\ZippyProfile --fresh
        docker_exec php artisan scout:import App\\ZippyProduct --fresh
        docker_exec php artisan scout:import App\\ZippyProductOffer --fresh
        docker_exec php artisan scout:import App\\Offer --fresh
        docker_exec php artisan scout:import App\\Marketplace\\Model\\MarketplaceItem --fresh
        ;;
    "typesense-reset")
        exec_commands typesense-flush
        exec_commands typesense-import
        ;;
    *)
        docker_exec --interactive "$@"
        ;;
    esac
}

function print_help() {
    echo "Usage: $0 COMMAND"
    echo
    echo "A script to manage your Docker container."
    echo
    echo "Commands:"
    echo "  init                     Initialize the application."
    echo "  fix                      Run the PHP-CS-Fixer."
    echo "  check                    Run the Svelte-check."
    echo "  test                     Run the application tests."
    echo "  tests-ai                 Run the AI integration test suite."
    echo "  routes-generate          Generate ziggy routes for the frontend."
    echo "  prettier                 Run prettier for the frontend."
    echo "  translations-generate    Generate translations in json file for the frontend."
    echo "  typesense-flush          Flush all Scout/Typesense indexes for every model."
    echo "  typesense-import         Import all models into Scout/Typesense indexes."
    echo "  typesense-reset          Flush and re-import all Scout/Typesense indexes."
    echo "  -h, --help  Show this help message."
    echo
    echo "Any other command will be passed directly to the Docker container."
}

function init() {
    if [[ $# -eq 0 || "$1" == "-h" || "$1" == "--help" ]]; then
        print_help
        exit 0
    fi

    check_docker || exit 1
    check_container || start_container || exit 1
    ensure_user || exit 1
    exec_commands "$@"
}

init "$@"
