<?php

namespace App\Http\Controllers\Auth;

use App\Helpers\PasswordHelper;
use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Validation\Rules;
use Inertia\Inertia;
use Inertia\Response;

class SetPasswordController extends Controller
{
    /**
     * Show the set password page.
     */
    public function create(Request $request, string $token): Response
    {
        $user = User::where('password_setup_token', $token)
            ->where('password_setup_expires_at', '>', now())
            ->first();

        if (! $user) {
            return Inertia::render('auth/set-password', [
                'token' => $token,
                'valid' => false,
                'message' => 'This password setup link has expired or is invalid. Please request a new one.',
            ]);
        }

        return Inertia::render('auth/set-password', [
            'token' => $token,
            'valid' => true,
            'email' => $user->email,
            'name' => $user->name,
        ]);
    }

    /**
     * Handle setting the password.
     */
    public function store(Request $request): RedirectResponse
    {
        // Find user first to get current name for unique validation
        $user = User::where('password_setup_token', $request->token)
            ->where('password_setup_expires_at', '>', now())
            ->first();

        if (! $user) {
            return back()->withErrors([
                'token' => 'This password setup link has expired or is invalid.',
            ]);
        }

        $request->validate([
            'token' => 'required|string',
            'name' => 'required|string|min:3|max:20|alpha_num|unique:users,name,' . $user->ID . ',ID',
            'password' => ['required', 'confirmed', Rules\Password::defaults()],
        ]);

        // Update username if changed
        $oldName = $user->name;
        if ($request->name !== $oldName) {
            $user->name = $request->name;
        }

        // Set the password using pw.sql changePasswd stored procedure
        DB::statement('CALL changePasswd(?, ?)', [
            $request->name,
            PasswordHelper::encryptPassword($request->name, $request->password),
        ]);

        $user->password_setup_token = null;
        $user->password_setup_expires_at = null;
        $user->save();

        // Send registration email with credentials
        $user->sendRegistrationEmail($request->password);

        // Log the user in
        Auth::login($user);

        return redirect()->route('dashboard');
    }

    /**
     * Show password setup pending page after registration.
     */
    public function pending(): Response
    {
        $email = session('password_setup_email');
        
        if (! $email) {
            return redirect()->route('login');
        }

        return Inertia::render('auth/password-setup-pending', [
            'email' => $email,
        ]);
    }
}
