<?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
{
    public function up(): void
    {
        Schema::table('plans', function (Blueprint $table) {
            // nullable bio_pages_limit (null = unlimited)
            $table->unsignedSmallInteger('bio_pages_limit')->nullable()->after('click_limit_monthly');

            // make numeric limits nullable so Agency can set null = unlimited
            $table->unsignedSmallInteger('workspace_limit')->nullable()->change();
            $table->unsignedSmallInteger('member_limit')->nullable()->change();
            $table->unsignedSmallInteger('custom_domain_limit')->nullable()->change();
            $table->unsignedInteger('link_limit')->nullable()->change();
        });

        // tier is already a string(32) column (added in 400000); no DDL change needed.
        // agency value is valid — string columns accept any value.
    }

    public function down(): void
    {
        // Revert agency → free so numeric limits can be restored safely
        DB::table('plans')->where('tier', 'agency')->update(['tier' => 'free']);

        // Fill NULLs with defaults before restoring NOT NULL constraints
        DB::table('plans')->whereNull('workspace_limit')->update(['workspace_limit' => 1]);
        DB::table('plans')->whereNull('member_limit')->update(['member_limit' => 1]);
        DB::table('plans')->whereNull('custom_domain_limit')->update(['custom_domain_limit' => 0]);
        DB::table('plans')->whereNull('link_limit')->update(['link_limit' => 50]);

        Schema::table('plans', function (Blueprint $table) {
            if (Schema::hasColumn('plans', 'bio_pages_limit')) {
                $table->dropColumn('bio_pages_limit');
            }
            $table->unsignedSmallInteger('workspace_limit')->default(1)->nullable(false)->change();
            $table->unsignedSmallInteger('member_limit')->default(1)->nullable(false)->change();
            $table->unsignedSmallInteger('custom_domain_limit')->default(0)->nullable(false)->change();
            $table->unsignedInteger('link_limit')->default(50)->nullable(false)->change();
        });
    }
};
