<?php

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

return new class extends Migration
{
    public function up(): void
    {
        DB::table('serenatas')
            ->select(['id', 'contact_phone_1', 'contact_phone_2'])
            ->orderBy('id')
            ->chunkById(200, function ($rows) {
                foreach ($rows as $row) {
                    $phone1 = PhoneNumber::normalize((string) ($row->contact_phone_1 ?? '')) ?: null;
                    $phone2 = PhoneNumber::normalize((string) ($row->contact_phone_2 ?? '')) ?: null;

                    DB::table('serenatas')
                        ->where('id', $row->id)
                        ->update([
                            'contact_phone_1' => $phone1,
                            'contact_phone_2' => $phone2,
                        ]);
                }
            });

        DB::table('customers')
            ->select(['id', 'mobile'])
            ->orderBy('id')
            ->chunkById(200, function ($rows) {
                foreach ($rows as $row) {
                    $mobile = PhoneNumber::normalize((string) ($row->mobile ?? '')) ?: null;

                    DB::table('customers')
                        ->where('id', $row->id)
                        ->update([
                            'mobile' => $mobile,
                        ]);
                }
            });
    }

    public function down(): void
    {
        // No-op: backfill irreversible by design.
    }
};
