<?php

namespace App\Services;

use App\Models\Department;
use Illuminate\Support\Str;

class RoleDepartmentResolver
{
    public function resolveDepartmentIdForRoles(array $roles, int $dealerId): ?int
    {
        $roles = array_values(array_unique($roles));
        if ($roles === []) {
            return null;
        }

        $config = config('mtt_role_department_map.role_to_department', []);
        $protectedDepartments = config('mtt_role_department_map.protected_departments', []);

        $departmentName = null;

        if (in_array('System Admin', $roles, true)) {
            $departmentName = $config['System Admin'] ?? 'System Administration';
        } else {
            foreach ($config as $roleName => $mappedDepartment) {
                if (in_array($roleName, $roles, true)) {
                    $departmentName = $mappedDepartment;
                    break;
                }
            }
        }

        if (!$departmentName) {
            return null;
        }

        $department = Department::query()
            ->where('dealer_id', $dealerId)
            ->where('name', $departmentName)
            ->first();

        if (!$department) {
            $code = Str::slug($departmentName, '_');
            $slug = Str::slug($departmentName);

            $department = Department::query()->create([
                'dealer_id' => $dealerId,
                'name' => $departmentName,
                'code' => $code,
                'slug' => $slug,
                'is_system' => in_array($departmentName, $protectedDepartments, true),
            ]);
        } elseif ($departmentName === 'System Administration' && !$department->is_system) {
            $department->is_system = true;
            $department->save();
        }

        return $department->id;
    }
}

