<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\Rules\Password;
use App\Models\Tenant;

class TenantUserController extends Controller
{
    /**
     * Create a user inside a tenant database.
     * Route: POST /admin/tenants/{tenant}/users
     */
    public function store(Request $request, Tenant $tenant)
    {
        $data = $request->validate([
            'name' => ['required', 'string', 'max:120'],
            'email' => ['required', 'email', 'max:190'],
            'password' => ['required', 'string', Password::min(8)],
            'role' => ['nullable', 'string'], // optional (admin by default)
        ]);

        $role = $data['role'] ?? 'admin';

        // Run inside tenant DB
        $created = null;
        $tenant->run(function () use (&$created, $data, $role) {
            $User = \App\Models\User::class;

            // prevent duplicates inside tenant
            if ($User::where('email', $data['email'])->exists()) {
                abort(422, 'A user with this email already exists in this tenant.');
            }

            $created = $User::create([
                'name' => $data['name'],
                'email' => $data['email'],
                'password' => Hash::make($data['password']),
            ]);

            // If you use spatie/permission inside tenant:
            if (method_exists($created, 'assignRole')) {
                $created->assignRole($role);
            }
        });

        return redirect()
            ->back()
            ->with('success', 'Tenant user created successfully.');
    }
}
