<?php

namespace Modules\Auth\Actions\Fortify;

use App\Traits\NotifiesAdmins;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Str;
use Illuminate\Validation\Rule;
use Laravel\Fortify\Contracts\CreatesNewUsers;
use Modules\Auth\Entities\User;
use Modules\Auth\Services\PhoneVerificationOtpService;
use Modules\Role\Entities\Role;
use Modules\User\Notifications\UserActivationNotification;
use Modules\User\Policies\UserPolicy;
use Exception;

class CreateNewUser implements CreatesNewUsers
{
    use PasswordValidationRules, NotifiesAdmins;

    public function __construct(
        protected PhoneVerificationOtpService $phoneVerificationOtpService,
    ) {}

    public function create(array $input): User
    {
        $phoneNumber = $this->phoneVerificationOtpService->normalizePhoneNumber($input['phone_number'] ?? '');

        Validator::make(array_merge($input, ['phone_number' => $phoneNumber]), [
            'name' => ['required', 'string', 'max:255'],
            'email' => [
                'required',
                'string',
                'email',
                'max:255',
                Rule::unique(User::class),
            ],
            'ic_number' => ['required', 'string', 'max:255'],
            'phone_number' => [
                ...$this->phoneVerificationOtpService->phoneNumberRules(),
                Rule::unique(User::class),
            ],
            'phone_verification_token' => ['required', 'string', 'size:64'],
            'password' => ['required', 'string', 'min:8'],
        ], [
            'phone_number.required' => 'Nombor telefon diperlukan.',
            'phone_number.regex' => 'Format nombor telefon tidak sah.',
            'phone_number.unique' => 'Nombor telefon ini telah didaftarkan.',
            'phone_verification_token.required' => 'Pengesahan nombor telefon diperlukan.',
        ])->validate();

        $this->phoneVerificationOtpService->consumeRegistrationToken(
            $phoneNumber,
            $input['phone_verification_token'],
        );

        $user = User::create([
            'name' => $input['name'],
            'uuid' => Str::uuid(),
            'email' => $input['email'],
            'password' => Hash::make($input['password']),
            'ic_number' => $input['ic_number'],
            'phone_number' => $phoneNumber,
            'phone_verified_at' => now(),
            'status' => 'pending',
        ]);

        // Assign role using Spatie permissions
        $role = Role::where('name', 'Anggota')->first();
        if ($role) {
            $user->assignRole($role);
        }

        if ($user->status === 'pending') {
            $this->notifyAdminsForActivation($user);
        }

        return $user;
    }

    /**
     * Notify users who can kemaskini pengguna about new user requiring activation.
     */
    private function notifyAdminsForActivation(User $newUser): void
    {
        try {
            $recipients = $this->getUsersWithPermission(UserPolicy::PERMISSION_UPDATE)
                ->where('id', '!=', $newUser->id);

            $sender = auth()->user() ?? $newUser;

            foreach ($recipients as $recipient) {
                try {
                    $recipient->notify(new UserActivationNotification($newUser, $sender));
                } catch (Exception $e) {
                    Log::error('Failed to send user activation notification: '.$e->getMessage());
                }
            }
        } catch (Exception $e) {
            Log::error('Failed to notify admins for user activation: '.$e->getMessage());
        }
    }

}
