<?php

declare(strict_types=1);

namespace App\Http\Controllers;

use App\Enums\UserTypes;
use App\Http\Controllers\Helpers\Permissions\UserPermissions;
use Hypervel\Http\Request;
use App\Models\User;


use App\Enums\UserActions;
use App\Traits\Roles;
use Hypervel\Support\Facades\Hash;
use Hypervel\Support\Facades\Validator;


class UserCreateController
{
    public function createUser(UserTypes $acct_type, Request $request)
    {
        // Step 1: Check if the current authenticated user has the permission to create a user
        $userType = auth()->user()->acct_type; // Assuming you're using the `acct_type` field for the current user's type



        if (!UserPermissions::isActionPermitted($acct_type, UserActions::CreateUser)) {
            return response()->json(['error' => 'Permission denied'], 403);
        }

        // Step 2: Validate incoming request data
        $validator = Validator::make($request->all(), [
            'name' => 'required|string|max:255',

            
            'email' => 'required|email|unique:users,email',
            'mobile_number' => 'required|string|max:15',
            'password' => 'required|string|min:8',
            'username' => 'nullable|string|unique:users,username',
            // Add any other validation rules needed
        ]);

        if ($validator->fails()) {
            return response()->json(['errors' => $validator->errors()], 422);
        }

        if ($acct_type instanceof UserTypes) {
            $acct_type = $acct_type->value;
        }

        if (!is_string($acct_type) || !$acct_type) {

        }

        // Step 3: Create the new user
        $user = User::create([
            'name' => $request->input('name'),
            'email' => $request->input('email'),
            'mobile_number' => $request->input('mobile_number'),
            'password' => Hash::make($request->input('password')),
            'acct_type' => $acct_type,
            'username' => $request->input('username'),
            'created_by' => auth()->user()->id, // Currently authenticated user
            // Add any other fields as needed
        ]);

        // Step 4: Handle user-specific logic based on their `acct_type`
        $this->handleUserTypeSpecificLogic($acct_type, $user);

        return response()->json([
            'message' => 'User created successfully',
            'user' => $user
        ], 201);
    }
}


