<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\File;

/**
 * Seeds an `addons` row for the bundled Instagram addon so it appears
 * in Admin → Addons without the admin needing to re-upload it as a ZIP.
 *
 * Runs AFTER 2026_05_26_120000_create_addons_table (lexicographic order).
 * Idempotent: skips if the row already exists. Status stays 'inactive'
 * so activation (and the channel-enum migration) is still an explicit
 * admin choice.
 */
return new class extends Migration {
    public function up(): void
    {
        if (DB::table('addons')->where('slug', 'instagram')->exists()) {
            return;
        }

        $manifestPath = base_path('addons/instagram/addon.json');
        if (!File::exists($manifestPath)) {
            return; // Bundled folder missing — nothing to register.
        }

        $manifest = json_decode(File::get($manifestPath), true);
        if (!is_array($manifest)) {
            return;
        }

        DB::table('addons')->insert([
            'slug' => $manifest['slug'] ?? 'instagram',
            'name' => $manifest['name'] ?? 'Instagram Direct Messages',
            'version' => $manifest['version'] ?? '1.0.0',
            'status' => 'inactive',
            'description' => $manifest['description'] ?? null,
            'author' => $manifest['author'] ?? null,
            'author_url' => $manifest['author_url'] ?? null,
            'manifest' => json_encode($manifest),
            'installed_at' => now(),
            'created_at' => now(),
            'updated_at' => now(),
        ]);
    }

    public function down(): void
    {
        DB::table('addons')->where('slug', 'instagram')->delete();
    }
};
