<?php

namespace App\Services\Badges;

class BadgeFormDataService
{
    public function __construct(
        protected BadgeUserLookupService $lookupService,
        protected BadgeTextFormatter $formatter
    ) {
    }

    public function build(?string $schoolYear, array $selectedUserIds = [], ?string $activeRole = null): array
    {
        $selectedUserIds = $this->formatter->normalizeIds($selectedUserIds);

        $users = $this->lookupService->fetchStaffList($schoolYear, $selectedUserIds);

        foreach ($users as &$u) {
            if (!isset($u['user_id'])) {
                if (isset($u['id'])) {
                    $u['user_id'] = (int) $u['id'];
                }
            }

            $rolesStr = $u['roles'] ?? '';
            if ($rolesStr === '' && isset($u['role_name'])) {
                $rolesStr = (string) $u['role_name'];
            }

            $u['roles_raw'] = $rolesStr;
            $u['roles'] = $this->formatter->formatRolesCsv($rolesStr);

            if (empty($u['role_name'])) {
                $parts = array_filter(array_map('trim', explode(',', $rolesStr)));
                $u['role_name'] = $parts[0] ?? '';
            }

            $u['role_name_raw'] = $u['role_name'];
            $u['role_name'] = $this->formatter->formatRole((string) $u['role_name']);

            $u['class_section_id'] = $u['class_section_id'] ?? null;
            $u['class_section_name'] = $u['class_section_name'] ?? null;
        }
        unset($u);

        foreach ($users as &$u) {
            $rolesDetect = strtolower($u['roles_raw'] ?? ($u['role_name_raw'] ?? ''));
            $isTeacherish = str_contains($rolesDetect, 'teacher') || preg_match('/\bta\b/', $rolesDetect);

            if ($isTeacherish && !empty($u['user_id'])) {
                $assign = $this->lookupService->getLatestClassForUser((int) $u['user_id'], $schoolYear);
                if ($assign) {
                    $u['class_section_id'] = $assign['class_section_id'] ?? null;
                    $u['class_section_name'] = $assign['class_section_name'] ?? null;
                }
            }
        }
        unset($u);

        $rolesTabs = [
            'teacher' => 'Teachers',
            'ta'      => 'Teacher Assistants',
            'admin'   => 'Admins',
            'staff'   => 'Staff',
        ];

        $activeRole = array_key_exists((string) $activeRole, $rolesTabs)
            ? (string) $activeRole
            : 'teacher';

        return [
            'users'            => $users,
            'schoolYears'      => $this->lookupService->getAvailableSchoolYears(),
            'selectedYear'     => $schoolYear,
            'selectedUserIds'  => $selectedUserIds,
            'rolesTabs'        => $rolesTabs,
            'active_role'      => $activeRole,
        ];
    }
}