<?php

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

/**
 * Free plan was originally seeded with `project_limit: null` (unlimited). The
 * Free tier exists as a try-before-you-buy entry point, not a free production
 * tier — capping it at 1 forces users who want a second project to pay. Pro
 * (10) and Scale (unlimited) are unchanged. Seed migration was patched in
 * lockstep so fresh installs land at 1 directly.
 */
return new class extends Migration
{
    public function up(): void
    {
        $row = DB::table('plans')->where('key', 'free')->first();
        if ($row === null) {
            return;
        }

        $features = json_decode($row->features ?? '{}', true);
        if (! is_array($features)) {
            $features = [];
        }
        $features['project_limit'] = 1;

        DB::table('plans')
            ->where('key', 'free')
            ->update([
                'features' => json_encode($features),
                'description' => '1 project. All editor features. Upgrade to export.',
                'updated_at' => now(),
            ]);
    }

    public function down(): void
    {
        $row = DB::table('plans')->where('key', 'free')->first();
        if ($row === null) {
            return;
        }

        $features = json_decode($row->features ?? '{}', true);
        if (! is_array($features)) {
            $features = [];
        }
        $features['project_limit'] = null;

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