pipeline {
    agent any

    environment {
        API_TOKEN = credentials('04f8a5d4-19fc-4ab3-979e-35bbb5b64611')
        ENV_FILE = '/usr/local/share/environment/api.env'
        COMPOSE_FILE = 'src/deploy/main/docker-compose.yaml'
        PHP_CONTAINER = 'project-php'
    }

    stages {
        stage('Clean') {
            steps {
                cleanWs()
            }
        }
        stage('Clone') {
            steps {
                sh """
                    git clone https://gitea.diffteam.online/PHP/LaravelSkeletonAPI.git src
                """
            }
        }
        stage('Environment') {
            steps {
                sh """
                    if [ -f "${ENV_FILE}" ]; then
                        cp "${ENV_FILE}" src/.env

                        echo ".env file copied successfully"
                    else
                        echo "ERROR: .env file not found at ${ENV_FILE}"

                        exit 1
                    fi
                """
            }
        }
        stage('Build') {
            steps {
                sh """
                    docker compose --env-file src/.env -f "${COMPOSE_FILE}" build
                """
            }
        }
        stage('Deploy') {
            steps {
                sh """
                    docker compose --env-file src/.env -f "${COMPOSE_FILE}" down --remove-orphans
                    docker compose --env-file src/.env -f "${COMPOSE_FILE}" up -d

                    docker exec "${PHP_CONTAINER}" php artisan migrate --force
                    docker exec "${PHP_CONTAINER}" php artisan optimize
                """
            }
        }
    }
}
