where('email', $mailbox)->first(); if ($existing) { return $existing; } $base = rtrim((string) config('identity.api_url'), '/'); $key = (string) config('identity.api_key'); if ($base === '' || $key === '') { throw new RuntimeException('Identity API is not configured.'); } $res = Http::withToken($key) ->acceptJson() ->timeout(10) ->get("{$base}/identity/profile", ['mailbox' => $mailbox]); if ($res->failed()) { throw new RuntimeException('Could not resolve the Ladill account for this mailbox.'); } $data = $res->json('data'); if (! is_array($data)) { throw new RuntimeException('Could not resolve the Ladill account for this mailbox.'); } $publicId = trim((string) ($data['public_id'] ?? '')); if ($publicId === '') { throw new RuntimeException('No Ladill account is linked to this mailbox.'); } return User::updateOrCreate( ['public_id' => $publicId], [ 'name' => trim((string) ($data['name'] ?? '')) ?: $mailbox, 'email' => $mailbox, 'avatar_url' => ($picture = trim((string) ($data['picture'] ?? ''))) !== '' ? $picture : null, ], ); } }