<?php

namespace App\Extensions\Concerns;

use App\Models\Extension;
use Illuminate\Support\Facades\App;
use Illuminate\Support\Facades\Schema;

trait ChecksExtensionInstallation
{
    /**
     * Check if an extension is installed before running down() migration
     *
     * @param string $extensionId
     * @return bool
     */
    protected function extensionIsInstalled(string $extensionId): bool
    {
        // If extensions table doesn't exist, we're in initial setup
        if (!Schema::hasTable('extensions')) {
            return false;
        }

        try {
            $record = Extension::where('extension_id', $extensionId)->first();
            return $record && ($record->installed ?? false);
        } catch (\Exception $e) {
            // If there's any error (e.g., database connection issues), skip rollback
            return false;
        }
    }

    /**
     * Skip rollback if extension is not installed
     *
     * Only applies to local/development environments to prevent errors.
     * In production, rollbacks will execute normally regardless of extension status.
     *
     * @param string $extensionId
     * @return bool Returns true if should skip rollback
     */
    protected function shouldSkipRollback(string $extensionId): bool
    {
        // In production, always allow rollbacks to execute
        if (App::environment('production')) {
            return false;
        }

        // In local/development, skip rollback if extension is not installed
        return !$this->extensionIsInstalled($extensionId);
    }
}
