<?php

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

/**
 * Seed `plans.max_seats` for the default Free / Pro / Scale rows (Δ4).
 *
 *   Free   → 1     (owner-only editing — the seat-cap fence; viewers free)
 *   Pro    → 5     (owner + up to 4 admins/editors; viewers unlimited)
 *   Scale  → NULL  (unlimited seats)
 *
 * The original billing-plans seed shipped `max_seats = 1` for EVERY plan, so
 * the seat gate would otherwise make every plan owner-only out of the box.
 * This migration bumps Pro/Scale to their real caps.
 *
 * Idempotent + guarded: only updates a row whose `max_seats` is STILL at the
 * original seeded value of `1` — so an admin who has already retuned a plan's
 * seats (e.g. set Pro to 10) is never clobbered by a re-run / later deploy.
 * Targets by `key`; admin-created plans are untouched.
 */
return new class extends Migration
{
    public function up(): void
    {
        // value === null means "set to NULL (unlimited)".
        $defaults = [
            'free' => 1,
            'pro' => 5,
            'scale' => null,
        ];

        foreach ($defaults as $key => $seats) {
            $row = DB::table('plans')->where('key', $key)->first();
            if ($row === null) {
                continue;
            }

            // Only seed rows still at the original `1` — preserve an admin's
            // later manual edit. (Free stays 1 either way.)
            if ((int) $row->max_seats !== 1) {
                continue;
            }

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

    public function down(): void
    {
        // Revert the bumped rows back to the original seeded value of 1,
        // mirroring the pre-team seed. Free was already 1.
        foreach (['free', 'pro', 'scale'] as $key) {
            DB::table('plans')
                ->where('key', $key)
                ->update([
                    'max_seats' => 1,
                    'updated_at' => now(),
                ]);
        }
    }
};
