<?php

declare(strict_types=1);

use Illuminate\Database\Migrations\Migration;
use Inside\Content\Facades\Schema;
use Inside\Host\Bridge\BridgeContentType;
use Inside\Host\Migrations\CreateContentTypes;
use Illuminate\Support\Facades\Artisan;

final class UpdateUserRelationsCardinality extends Migration
{
    use CreateContentTypes;

    public function up(): void
    {
        $bridge = new BridgeContentType();

        collect(Schema::getRelations('users'))
            ->map(fn (string $relation) => str($relation)->snake()->toString())
            ->each(function (string $relation) use ($bridge) {
                $bridge->switchCardinalityFromUnaryToMultiple(type: 'users', fieldName: $relation, force: true);
                $bridge->contentTypeUpdateField(type: 'users', fieldName: $relation, options: [
                    'title' => Schema::getFieldOptions(modelName: 'users', fieldName: $relation)['title'],
                    'cardinality' => -1
                ]);
            });

        Artisan::call('models:rebuild');
    }
}
