<?php

namespace Database\Seeders;

use App\Enums\UserRole;
use App\Models\Role;
use App\Models\User;
use Illuminate\Database\Seeder;

class ManagerUsersSeeder extends Seeder
{
    public function run(): void
    {
        $managerRole = Role::query()->where('name', UserRole::Manager->value)->first();
        $residentRole = Role::query()->where('name', UserRole::Resident->value)->first();

        $manager = User::query()->firstOrCreate(
            ['messenger_user_id' => 'manager-seed'],
            [
                'messenger_platform' => 'bale',
                'full_name' => 'Building Manager',
                'mobile' => config('sharjino.manager_mobile'),
                'role' => UserRole::Manager->value,
                'is_active' => true,
            ]
        );

        if ($managerRole) {
            $manager->roles()->syncWithoutDetaching([$managerRole->id]);
        }

        $managerIds = array_filter(explode(',', (string) config('services.bale.manager_ids', '')));
        foreach ($managerIds as $managerId) {
            $user = User::query()->firstOrCreate(
                ['messenger_user_id' => trim($managerId)],
                [
                    'messenger_platform' => 'bale',
                    'role' => UserRole::Manager->value,
                    'is_active' => true,
                ]
            );

            $roleIds = [];
            if ($managerRole) {
                $roleIds[] = $managerRole->id;
            }
            if ($residentRole) {
                $roleIds[] = $residentRole->id;
            }
            if ($roleIds !== []) {
                $user->roles()->syncWithoutDetaching($roleIds);
            }
        }
    }
}
