<?php
/**
 * Migration Class
 *
 * @version     1.0.$Revision:$
 * @version     SVN: $Id:$
 * @package     bplan-base/globals
 * @subpackage  Migrations
 * @author      Emilio Cannarozzo <emilio.cannarozzo@bplan-solutions.de>
 * @author      Wassilios Meletiadis <wassilios.meletiadis@bplan-solutions.de>
 * @copyright   Copyright (C) 2025 bplan-solutions GmbH & Co. KG <https://www.bplan-solutions.de/>
 * /Δ\
 */


use BplanBase\CodeGenerator\Loaders\CodeGenerator;
use BplanBase\Globals\Enums\UserAccessLevel;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;


/**
 * Migration Class
 *
 * @author      Emilio Cannarozzo <emilio.cannarozzo@bplan-solutions.de>
 * @author      Wassilios Meletiadis <wassilios.meletiadis@bplan-solutions.de>
 */
return new class extends Migration
{

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

    } // down()


    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('tenant_user', function (Blueprint $Table) {
            $Table->id();
            $Table->uuid('uuid');

            $Table->timestamp('created_at');
            $Table->timestamp('updated_at');

            $Table->enum('access_level', array_column(UserAccessLevel::cases(), 'name'))->default('Staff');
            $Table->foreignId('tenant_id')->constrained(table: 'tenants', indexName: 'tenant_user_FK_tenant_id');
            $Table->foreignId('user_id')->constrained(table: 'users',     indexName: 'tenant_user_FK_user_id');

            $Table->index('tenant_id',               'tenant_user_FKI_tenant_id');
            $Table->index('user_id',                 'tenant_user_FKI_user_id');
            $Table->unique(['tenant_id', 'user_id'], 'tenant_user_UKI_tenant_user');
            $Table->unique('uuid',                   'tenant_user_UKI_uuid');

            new CodeGenerator($Table, [
                'columns' => [
                    'user_id' => [
                        'guarded' => true,
                        'sortable' => true,
                        // 'relationName' => 'assigned-user',              // Tenant-User-Model Relationenmethode, Standard: users()
                        'reverseRelationName' => 'assigned-users',      // Tenant-Model Relationenmethode, Standard: users()
                    ]
                ],
                'exclude' => [
                    'laravel.permission-seeder',
                    'livewire.*',
                ],
                'pivot' => [
                    'appends' => true,
                    'relations' => [
                        'tenant_id' => 'tenants',
                        'user_id' => 'users',
                    ],
                ],
                'routing' => [
                    'terminal' => 'readOnly',
                ],

            ]);

        });
    } // up()

};
