<?php

namespace App\Services;

use App\Models\Hub;
use App\Models\User;
use App\Services\Auth\EmailVerificationService;
use App\Support\AuthVerification;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;

// ══════════════════════════════════════════════════════════════════
//  InPractice — RegisterService
//  Location: app/Services/RegisterService.php
//
//  Contains ALL business logic for user registration.
//  The controller calls one method and gets back the new User.
//
//  What this service does:
//    1. Creates the user record
//    2. Attaches the selected hubs (first selected = primary)
//    3. Optional OTP email (AUTH_EMAIL_VERIFICATION_* in .env)
//
//  Wrapped in a DB transaction — if hub attachment fails,
//  the user record is also rolled back. No orphaned users.
// ══════════════════════════════════════════════════════════════════

class RegisterService
{
    /**
     * Register a new member.
     *
     * @param  array  $data  Validated data from StoreRegisterRequest
     * @return User          The newly created and persisted user
     */
    public function register(array $data): User
    {
        return DB::transaction(function () use ($data) {

            // ── Step 1: Create the user ────────────────────────
            $user = User::create([
                'name'             => $data['name'],
                'nickname'         => $data['nickname'],
                'email'            => $data['email'],
                'password'         => Hash::make($data['password']),
                'profession'       => $data['profession'] ?? null,
                'experience_level' => $data['experience_level'],
                'language'         => $data['language']  ?? 'en',
                'theme'            => $data['theme']      ?? 'navy',
                'role'             => 'member',
                'is_active'        => true,
            ]);

            // ── Step 2: Attach hubs ────────────────────────────
            // Resolve hub slugs to hub IDs
            $hubSlugs = $data['hubs'];
            $hubs     = Hub::whereIn('slug', $hubSlugs)
                           ->where('is_active', true)
                           ->get();

            // Attach each hub — first one in the array is primary
            foreach ($hubs as $index => $hub) {
                $user->hubs()->attach($hub->id, [
                    'is_primary' => $index === 0,
                    'joined_at'  => now(),
                ]);
            }

            // ── Step 3: Email verification (configurable via .env) ──
            if (AuthVerification::enabled()) {
                if (AuthVerification::sendOnRegister()) {
                    app(EmailVerificationService::class)->issueAndSend($user);
                }
            } else {
                $user->forceFill(['email_verified_at' => now()])->save();
            }

            return $user;
        });
    }
}
