<?php

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

return new class extends Migration
{
    public function up(): void
    {
        // Mirrors the pattern of 2026_05_09_000010_seed_plan_storage_bytes_limit
        // and 2026_05_26_..._seed_can_use_premium_kits_feature.
        // Free stays locked out (upgrade gate). Pro/Scale get generous pools;
        // admins can tune per-plan via the Plan editor after install.
        $map = [
            'free'  => ['can_use_ai' => false, 'ai_tokens_monthly' => 0],
            'pro'   => ['can_use_ai' => true,  'ai_tokens_monthly' => 300000],
            'scale' => ['can_use_ai' => true,  'ai_tokens_monthly' => null],   // null = unlimited
        ];

        foreach ($map as $key => $values) {
            $plan = DB::table('plans')->where('key', $key)->first();
            if (! $plan) {
                continue;
            }

            $features = json_decode($plan->features ?? '{}', true) ?? [];
            $features['can_use_ai']        = $values['can_use_ai'];
            $features['ai_tokens_monthly'] = $values['ai_tokens_monthly'];

            DB::table('plans')
                ->where('key', $key)
                ->update(['features' => json_encode($features)]);
        }
    }

    public function down(): void
    {
        foreach (['free', 'pro', 'scale'] as $key) {
            $plan = DB::table('plans')->where('key', $key)->first();
            if (! $plan) {
                continue;
            }

            $features = json_decode($plan->features ?? '{}', true) ?? [];
            unset($features['can_use_ai'], $features['ai_tokens_monthly']);

            DB::table('plans')
                ->where('key', $key)
                ->update(['features' => json_encode($features)]);
        }
    }
};
