<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Models\Invite;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\Str;

class InviteController extends Controller
{
    /**
     * Show the registration form for invite.
     */
    public function showRegistrationForm($token)
    {
        // Find the invite by token
        $invite = Invite::where('token', $token)->first();
        
        // Check if invite exists and is not expired
        if (!$invite || ($invite->expires_at && $invite->expires_at < now()) || $invite->used) {
            return redirect()->route('login')->with('error', 'Invalid or expired invite token.');
        }
        
        // Pass the invite data to the registration form
        return view('auth.register', compact('invite'));
    }
    
    /**
     * Handle registration with invite token.
     */
    public function register(Request $request, $token)
    {
        // This method is now handled by RegisteredUserController@store
        // We'll redirect to the proper route
        return redirect()->route('register', ['invite_token' => $token]);
    }
    
    /**
     * Create a new invite (accessible only to authorized roles).
     */
    public function store(Request $request)
    {
        // Rate limiting
        $throttleKey = 'invite-create|' . $request->ip();
        
        if (RateLimiter::tooManyAttempts($throttleKey, 10)) {
            return response()->json(['error' => 'Too many requests. Please try again later.'], 429);
        }
        
        // Authorization check
        if (!auth()->user()->hasAnyRole(['superadmin', 'brand_admin'])) {
            return response()->json(['error' => 'Unauthorized'], 403);
        }
        
        $request->validate([
            'email' => ['required', 'string', 'email', 'max:255'],
            'role' => ['required', 'in:superadmin,brand_admin,agency_admin,creator,user'],
            'expires_in_days' => ['nullable', 'integer', 'min:1', 'max:365'],
        ]);
        
        // For brand_admin, ensure they can only invite users to their own tenant
        $tenantId = null;
        if (auth()->user()->hasRole('brand_admin')) {
            $tenantId = auth()->user()->tenant_id;
        } else {
            // For superadmin, tenant_id is optional
            $tenantId = $request->tenant_id ?? null;
        }
        
        // Create the invite
        $invite = Invite::create([
            'tenant_id' => $tenantId,
            'email' => $request->email,
            'token' => Str::random(32),
            'role' => $request->role,
            'expires_at' => $request->expires_in_days ? now()->addDays($request->expires_in_days) : null,
        ]);
        
        // Log the invite creation
        \App\Models\AuditLog::create([
            'actor_id' => auth()->id(),
            'action' => 'invite_created',
            'target_type' => 'invite',
            'target_id' => $invite->id,
            'meta' => [
                'email' => $request->email,
                'role' => $request->role,
                'tenant_id' => $tenantId,
            ]
        ]);
        
        // Increment rate limiter
        RateLimiter::hit($throttleKey);
        
        // TODO: Send email to the invited user (placeholder)
        // Mail::to($request->email)->send(new InviteEmail($invite));
        
        return response()->json([
            'message' => 'Invite created successfully',
            'invite_token' => $invite->token,
            'invite_link' => route('invite.register', $invite->token),
        ]);
    }
}
