<?php

namespace App\Services;

use App\Models\UserModel;
use App\Support\EmailAddress;

class AuthSessionService
{
    /**
     * @param array<string, mixed> $user
     */
    public function establish(array $user, bool $regenerate = true): void
    {
        $session = session();
        if ($regenerate) {
            $session->regenerate(true);
        }

        $session->set([
            'user_id'                       => (int) $user['id'],
            'email'                         => (string) $user['email'],
            'profile_onboarding_completed'  => (int) $user['profile_onboarding_completed'],
        ]);
    }

    /**
     * Find or create the user after a successful OTP.
     *
     * @return array<string, mixed>|null Inactive users return null.
     */
    public function identifyOrCreate(string $email): ?array
    {
        $email = EmailAddress::normalize($email);
        $users = new UserModel();
        $user  = $users->findByEmail($email);

        if ($user === null) {
            $id = $users->insert([
                'email'                         => $email,
                'profile_onboarding_completed'  => 0,
                'is_active'                     => 1,
                'last_login_at'                 => date('Y-m-d H:i:s'),
            ], true);

            return $users->find($id);
        }

        if ((int) $user['is_active'] !== 1) {
            return null;
        }

        $users->update($user['id'], [
            'last_login_at' => date('Y-m-d H:i:s'),
        ]);

        return $users->find($user['id']);
    }

    public function authenticatedDestination(): string
    {
        return (int) session()->get('profile_onboarding_completed') === 1
            ? '/dashboard'
            : '/profile/onboarding';
    }
}
