<?php

namespace PluginsNameSpaces\Hooks\CLI;

use PluginsNameSpaces\Database\DBMigrator;
use PluginsNameSpaces\Framework\Console\Packager;

/**
 * WP-CLI commands for the plugin.
 *
 * Registered as `wp __PLUGIN_NAME__ <command>` when WP-CLI is present.
 */
class Commands
{
    /**
     * Run database migrations.
     *
     * ## EXAMPLES
     *
     *     wp __PLUGIN_NAME__ migrate
     *
     * @when after_wp_load
     */
    public function migrate($args, $assoc_args)
    {
        DBMigrator::migrate();
        update_option('__SNAKE_NAME___db_version', __CONST_PREFIX___DB_VERSION);

        \WP_CLI::success('Migrations complete.');
    }

    /**
     * Show plugin information.
     *
     * ## EXAMPLES
     *
     *     wp __PLUGIN_NAME__ info
     *
     * @when after_wp_load
     */
    public function info($args, $assoc_args)
    {
        \WP_CLI::log('Plugin:  ' . __SNAKE_NAME___config('app.name'));
        \WP_CLI::log('Version: ' . __SNAKE_NAME___config('app.version'));
        \WP_CLI::log('DB ver:  ' . get_option('__SNAKE_NAME___db_version', 'n/a'));
    }

    /**
     * Build a distributable plugin ZIP.
     *
     * Runs the framework Packager against the plugin root, excluding dev files
     * per the baseline and .distignore. Run `composer install --no-dev` and
     * `npm run build` first so the archive ships a lean vendor/ and built assets.
     *
     * ## OPTIONS
     *
     * [--output=<dir>]
     * : Directory to write the ZIP to. Defaults to the plugin root.
     *
     * ## EXAMPLES
     *
     *     wp __PLUGIN_NAME__ build
     *     wp __PLUGIN_NAME__ build --output=/tmp
     *
     * @when after_wp_load
     */
    public function build($args, $assoc_args)
    {
        try {
            $packager = new Packager(
                rtrim(__CONST_PREFIX___PATH, '/\\'),
                __SNAKE_NAME___config('app.slug'),
                __SNAKE_NAME___config('app.version'),
                isset($assoc_args['output']) ? $assoc_args['output'] : null
            );

            $zip = $packager->build();
        } catch (\Throwable $e) {
            \WP_CLI::error($e->getMessage());
            return;
        }

        \WP_CLI::success('Built ' . $zip);
    }
}
