<?php

namespace App\Apps\Versionmgr;

use App\Apps\Versionmgr\Models\SystemVersion;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class Install
{
    public function install(): void
    {
        $this->runMigrations();
        $this->initSystemVersion();
    }

    public function uninstall(): void
    {
        $this->rollbackMigrations();

        Cache::forget('versionmgr_latest');
        Cache::forget('system_current_version');
        Cache::forget('system_current_build');
    }

    public function upgrade(string $fromVersion, string $toVersion): void
    {
        $this->runMigrations();
    }

    protected function runMigrations(): void
    {
        $migrationsPath = __DIR__ . '/Migrations';
        $migrationFiles = glob($migrationsPath . '/*.php');

        foreach ($migrationFiles as $file) {
            $migrationName = pathinfo($file, PATHINFO_FILENAME);

            if (DB::table('migrations')->where('migration', $migrationName)->exists()) {
                continue;
            }

            $migration = require $file;
            if (method_exists($migration, 'up')) {
                try {
                    $migration->up();

                    DB::table('migrations')->insert([
                        'migration' => $migrationName,
                        'batch' => DB::table('migrations')->max('batch') + 1,
                    ]);
                } catch (\Throwable $e) {
                    Log::error('应用迁移执行失败', [
                        'app' => 'versionmgr',
                        'file' => basename($file),
                        'error' => $e->getMessage(),
                    ]);
                }
            }
        }
    }

    protected function rollbackMigrations(): void
    {
        $migrationsPath = __DIR__ . '/Migrations';
        $migrationFiles = glob($migrationsPath . '/*.php');

        foreach (array_reverse($migrationFiles) as $file) {
            $migrationName = pathinfo($file, PATHINFO_FILENAME);

            if (!DB::table('migrations')->where('migration', $migrationName)->exists()) {
                continue;
            }

            $migration = require $file;
            if (method_exists($migration, 'down')) {
                try {
                    $migration->down();

                    DB::table('migrations')->where('migration', $migrationName)->delete();
                } catch (\Throwable $e) {
                    Log::error('Versionmgr迁移回滚失败', [
                        'file' => basename($file),
                        'error' => $e->getMessage(),
                    ]);
                }
            }
        }
    }

    protected function initSystemVersion(): void
    {
        $currentVersion = config('app.version', '5.0.1');

        SystemVersion::where('status', 1)->update(['status' => 0]);

        SystemVersion::create([
            'version' => $currentVersion,
            'build' => date('YmdHis'),
            'changelog' => '初始安装版本',
            'upgrade_type' => '手动升级',
            'status' => 1,
            'upgrade_result' => 1,
            'detail' => ['type' => 'init'],
        ]);
    }
}
