<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Default builder URL (TitanSystems hosted service).
     */
    private const DEFAULT_BUILDER_URL = 'https://appy-builder.titansystems.ph';

    /**
     * Default builder port (HTTPS).
     */
    private const DEFAULT_BUILDER_PORT = 443;

    /**
     * Run the migrations.
     */
    public function up(): void
    {
        // 1. Add the is_default column
        Schema::table('app_builders', function (Blueprint $table) {
            $table->boolean('is_default')->default(false)->after('credit_cost');
            $table->index('is_default');
        });

        // 2. Ensure default builder exists (handles both fresh installs and v1.0 upgrades)
        $this->ensureDefaultBuilderExists();
    }

    /**
     * Ensure a default builder exists after migration.
     *
     * For v1.0 upgrades: If a builder with the TitanSystems URL exists, mark it as default.
     * For fresh installs or v1.0 sites without TitanSystems builder: Insert a new default builder.
     */
    private function ensureDefaultBuilderExists(): void
    {
        // Check if a builder with the TitanSystems URL already exists
        $existingTitanBuilder = DB::table('app_builders')
            ->where('url', self::DEFAULT_BUILDER_URL)
            ->first();

        if ($existingTitanBuilder) {
            // Mark existing TitanSystems builder as default
            DB::table('app_builders')
                ->where('id', $existingTitanBuilder->id)
                ->update(['is_default' => true]);
        } else {
            // Insert new default builder
            $platforms = $this->getActivePlatformIds();

            DB::table('app_builders')->insert([
                'name' => 'Default Builder',
                'url' => self::DEFAULT_BUILDER_URL,
                'port' => self::DEFAULT_BUILDER_PORT,
                'server_key' => 'dynamic', // Actual key comes from purchase_code via model accessor
                'max_queue' => 5,
                'platforms' => json_encode($platforms),
                'status' => 'active',
                'credit_cost' => 1,
                'is_default' => true,
                'current_builds_count' => 0,
                'total_builds_processed' => 0,
                'created_at' => now(),
                'updated_at' => now(),
            ]);
        }
    }

    /**
     * Get active platform IDs from PluginManager, with fallback.
     */
    private function getActivePlatformIds(): array
    {
        try {
            $pluginManager = app(\App\Services\PluginManager::class);
            $platforms = $pluginManager->getActivePlatforms()
                ->map(fn ($p) => $p->getPlatformId())
                ->values()
                ->toArray();

            return ! empty($platforms) ? $platforms : ['android-webview'];
        } catch (\Exception $e) {
            // Fallback if PluginManager not available (e.g., during initial migration)
            return ['android-webview'];
        }
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        // Remove the default builder that was auto-created by this migration
        // Only delete if it matches our URL to avoid deleting user-modified builders
        DB::table('app_builders')
            ->where('is_default', true)
            ->where('url', self::DEFAULT_BUILDER_URL)
            ->delete();

        Schema::table('app_builders', function (Blueprint $table) {
            $table->dropIndex(['is_default']);
            $table->dropColumn('is_default');
        });
    }
};
