<?php

declare(strict_types=1);

use Hyperf\Database\Schema\Blueprint;
use Hypervel\Database\Migrations\Migration;
use Hypervel\Support\Facades\Schema;
use Hypervel\Support\Facades\DB;
use Hypervel\Support\Str;

return new class extends Migration {
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('user_infos', function (Blueprint $table) {
            $table->id();
            $table->string('hashkey', 300)->unique();
            $table->unsignedBigInteger('user_id')->unique();
            $table->string('firstname')->nullable();
            $table->string('middlename')->nullable();
            $table->string('lastname')->nullable();
            $table->string('fullname')->nullable();
            $table->string('landline')->nullable();
            $table->string('mobile')->nullable();
            $table->string('email')->nullable();
            $table->string('alt_email')->nullable();
            $table->string('alt_landline')->nullable();
            $table->string('alt_mobile')->nullable();
            $table->string('facebook_url')->nullable();
            $table->json('bank_details')->nullable();
            $table->json('addresses')->nullable();
            $table->json('other_details')->nullable();
            $table->boolean('is_active')->default(true);
            $table->unsignedBigInteger('created_by')->nullable();
            $table->unsignedBigInteger('updated_by')->nullable();

            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
            $table->foreign('created_by')->references('id')->on('users')->onDelete('set null');
            $table->foreign('updated_by')->references('id')->on('users')->onDelete('set null');

            $table->timestamps();
        });

        // Backfill existing users
        $users = DB::table('users')->get();
        foreach ($users as $user) {
            DB::table('user_infos')->insert([
                'hashkey' => Str::uuid()->toString() . Str::random(100),
                'user_id' => $user->id,
                'fullname' => $user->fullname ?? $user->name,
                'email' => $user->email,
                'mobile' => $user->mobile_number,
                'created_at' => date('Y-m-d H:i:s'),
                'updated_at' => date('Y-m-d H:i:s'),
                'is_active' => true,
            ]);
        }
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('user_infos');
    }
};
