<?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\Role\Entities\Role;
use Modules\User\Notifications\UserActivationNotification;
use Modules\Auth\Services\EmailVerificationOtpService;
use Exception;

class CreateNewUser implements CreatesNewUsers
{
    use PasswordValidationRules, NotifiesAdmins;

    /**
     * Validate and create a newly registered user.
     *
     * @param  array<string, string>  $input
     */
    public function create(array $input): User
    {
        Validator::make($input, [
            'name' => ['required', 'string', 'max:255'],
            'email' => [
                'required',
                'string',
                'email',
                'max:255',
                Rule::unique(User::class),
            ],
            'ic_number' => ['required', 'string', 'max:255'],
            'password' => ['required', 'string', 'min:8'],
        ])->validate();

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

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

        app(EmailVerificationOtpService::class)->send($user);

        // Send notification to admins if user requires activation
        if ($user->status === 'pending') {
            $this->notifyAdminsForActivation($user);
        }

        return $user;
    }

    /**
     * Notify admins about new user requiring activation
     */
    private function notifyAdminsForActivation(User $newUser): void
    {
        try {
            $adminRoles = ['PENTADBIR', 'PS 2 KJC', 'PS 2 ALAT'];
            
            // Get users with specific roles plus admins (PENTADBIR and DEVELOPER)
            $adminUsers = $this->getUsersWithRolesAndAdmins($adminRoles);

            $sender = auth()->user() ?? $newUser; // Use current user as sender, or new user if no auth

            foreach ($adminUsers as $admin) {
                try {
                    $admin->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());
        }
    }
}
