<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

/**
 * state (and country) on the address tables were created NOT NULL with no
 * usable default, but neither the registration form nor the guest checkout
 * flow reliably provides a state/county, so the insert sent NULL and failed
 * under strict SQL mode with:
 *
 *     SQLSTATE[23000]: 1048 Column 'state' cannot be null
 *
 *  - members_addresses: hit on registration (MemberManager::save()).
 *  - basket_address: hit when a logged-in member's state is copied into the
 *    basket billing address by Member::setBasketDetails() during a
 *    guest-basket takeover on login.
 *  - order_address: hit at checkout, where Order::newOrder() copies the basket
 *    address verbatim into the order address.
 *
 * Rather than make the columns nullable, keep them NOT NULL and give them a
 * sensible default: state defaults to '' (optional for UK addresses) and
 * country defaults to 'GB' (callers already hard-default it to 'GB', and it
 * should never be null). This is enforced by the database regardless of which
 * code path performs the insert, and is backed up by matching model defaults
 * on the address models.
 */
return new class extends Migration
{
    public function up(): void
    {
        foreach (['members_addresses', 'basket_address', 'order_address'] as $tableName) {
            Schema::table($tableName, function (Blueprint $table) {
                $table->string('state')->default('')->nullable(false)->change();
                $table->string('country')->default('GB')->nullable(false)->change();
            });
        }
    }

    public function down(): void
    {
        // Restore the original column definitions from the install migration:
        // members_addresses had no defaults on either column; basket_address
        // and order_address had country default('') and state with no default.
        Schema::table('members_addresses', function (Blueprint $table) {
            $table->string('state')->default(null)->nullable(false)->change();
            $table->string('country')->default(null)->nullable(false)->change();
        });

        foreach (['basket_address', 'order_address'] as $tableName) {
            Schema::table($tableName, function (Blueprint $table) {
                $table->string('state')->default(null)->nullable(false)->change();
                $table->string('country')->default('')->nullable(false)->change();
            });
        }
    }
};
