<?php

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

return new class extends Migration
{
    /**
     * Make zip_code nullable — Mozambique does not commonly use postal codes.
     * SQLite requires a full table rebuild; Laravel handles this automatically
     * when using ->change() with the built-in column modifier support.
     */
    public function up(): void
    {
        // For SQLite we use a raw approach: recreate the table.
        // First check if we're running on SQLite.
        $driver = DB::getDriverName();

        if ($driver === 'sqlite') {
            // Rename original table
            DB::statement('ALTER TABLE customer_addresses RENAME TO customer_addresses_old');

            // Re-create with zip_code nullable
            DB::statement('
                CREATE TABLE customer_addresses (
                    id INTEGER PRIMARY KEY AUTOINCREMENT,
                    customer_id INTEGER NOT NULL,
                    label VARCHAR(50) NULL,
                    address_line1 VARCHAR(255) NOT NULL,
                    address_line2 VARCHAR(255) NULL,
                    city VARCHAR(100) NOT NULL,
                    state VARCHAR(100) NOT NULL,
                    zip_code VARCHAR(20) NULL,
                    country VARCHAR(100) NULL,
                    phone VARCHAR(20) NULL,
                    is_default BOOLEAN NOT NULL DEFAULT 0,
                    created_at DATETIME NULL,
                    updated_at DATETIME NULL,
                    FOREIGN KEY (customer_id) REFERENCES customers(id) ON DELETE CASCADE
                )
            ');

            // Copy data
            DB::statement('
                INSERT INTO customer_addresses
                SELECT id, customer_id, label, address_line1, address_line2,
                       city, state, zip_code, country, phone, is_default,
                       created_at, updated_at
                FROM customer_addresses_old
            ');

            // Drop old table
            DB::statement('DROP TABLE customer_addresses_old');
        } else {
            // MySQL / PostgreSQL
            Schema::table('customer_addresses', function (Blueprint $table) {
                $table->string('zip_code', 20)->nullable()->change();
            });
        }
    }

    public function down(): void
    {
        // Reverting to NOT NULL would break existing NULL rows — skip on SQLite
        if (DB::getDriverName() !== 'sqlite') {
            Schema::table('customer_addresses', function (Blueprint $table) {
                $table->string('zip_code', 20)->nullable(false)->change();
            });
        }
    }
};
