<?php

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

class IideClenRoles extends Migration
{
    public function up(): void
    {
        $allowedEnvUrls = [
            'https://iide.docker.localhost',
            'https://iide.dev.intranet-inside.fr',
            'https://iide.pp.intranet-inside.fr',
            'https://iide.pp.intranet-inside.com'
        ];
        $appDomain = config('app.url');
        if (!in_array($appDomain, $allowedEnvUrls)) {
            return;
        }

        $subsidiaries = type_to_class('subsidiaries')::all()->pluck('uuid_host')->toArray();
        DB::table('inside_roles')->get()->each(function ($role, $index) use ($subsidiaries) {
            if ($role->is_automatic == 1 && str_starts_with($role->condition, 'subsidiaries:')) {

                // Récupère la partie après "subsidiaries:"
                $raw = substr($role->condition, strlen('subsidiaries:'));
                $raw = str_replace('not:', '', $raw);
                $ids = explode('&', $raw);
                $newCondition = 'subsidiaries:' . $subsidiaries[$index];
                $role = \Inside\Permission\Models\Role::find($role->id);
                $role->update([
                    'condition' => $newCondition
                ]);
            }
        });
    }
}
