<?php

namespace App\Services\Roles;

use App\Models\Staff;
use App\Models\User;
use Illuminate\Support\Facades\Log;

class RoleStaffService
{
    public function syncStaffRecord(User $user, array $newRoleNames): void
    {
        $excludedRoles = ['parent', 'student', 'guest'];
        $staffRoles = array_values(array_unique(array_filter(
            array_map(
                static fn ($role) => trim((string) $role),
                $newRoleNames
            ),
            static fn ($role) => $role !== '' && !in_array(strtolower($role), $excludedRoles, true)
        )));
        $activeRole = !empty($staffRoles) ? strtolower((string) $staffRoles[0]) : 'inactive';

        $email = $this->generateUniqueStaffEmail($user->firstname ?? '', $user->lastname ?? '', (int) $user->id);

        $payload = [
            'user_id' => (int) $user->id,
            'firstname' => $user->firstname ?? '',
            'lastname' => $user->lastname ?? '',
            'email' => $email,
            'phone' => $user->cellphone ?? '',
            'role_name' => $this->compactRoleList($staffRoles),
            'active_role' => $activeRole,
            'school_year' => $user->school_year ?? '',
        ];

        $saved = Staff::upsertStaff($payload);
        if (!$saved) {
            Log::warning('Failed to upsert staff record.', ['user_id' => $user->id]);
        }
    }

    /**
     * Fit the current staff role list into the legacy `staff.role_name` field.
     */
    private function compactRoleList(array $roles, int $maxLength = 100): string
    {
        if ($roles === []) {
            return 'inactive';
        }

        $out = '';
        foreach ($roles as $role) {
            $next = $out === '' ? $role : $out . ', ' . $role;
            if (strlen($next) > $maxLength) {
                break;
            }
            $out = $next;
        }

        return $out !== '' ? $out : substr((string) $roles[0], 0, $maxLength);
    }

    private function generateUniqueStaffEmail(string $firstname, string $lastname, int $userId): string
    {
        $domain = '@alrahmaisgl.org';

        $firstname = strtolower(preg_replace('/[^a-z]/i', '', $firstname));
        $lastname = strtolower(preg_replace('/[^a-z]/i', '', $lastname));

        $min = 1;
        $max = max(1, strlen($firstname));
        $base = '';
        $email = '';

        for ($i = $min; $i <= $max; $i++) {
            $base = substr($firstname, 0, $i) . $lastname;
            $email = $base . $domain;

            $exists = Staff::query()
                ->where('email', $email)
                ->where('user_id', '!=', $userId)
                ->exists();
            if (!$exists) {
                return $email;
            }
        }

        return $base . $userId . $domain;
    }
}
