<?php

namespace App\Http\Controllers\Auth;

use App\Enums\UserRole;
use App\Http\Controllers\Controller;
use App\Models\Business;
use App\Models\User;
use App\Services\Audit\ActivityLogger;
use Illuminate\Auth\Events\Registered;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Validation\Rules\Password;
use Illuminate\View\View;

class RegisteredBusinessController extends Controller
{
    public function create(): View
    {
        return view('auth.register');
    }

    public function store(Request $request, ActivityLogger $logger): RedirectResponse
    {
        $validated = $request->validate([
            'business_name' => ['required', 'string', 'max:160'],
            'owner_name' => ['required', 'string', 'max:120'],
            'phone' => ['nullable', 'string', 'max:40'],
            'email' => ['required', 'email', 'max:255', 'unique:users,email'],
            'password' => ['required', 'confirmed', Password::defaults()],
            'terms' => ['accepted'],
        ]);

        $user = User::query()->create([
            'name' => $validated['owner_name'],
            'email' => $validated['email'],
            'password' => $validated['password'],
            'role' => UserRole::BusinessOwner->value,
        ]);

        event(new Registered($user));

        Auth::login($user);

        $business = Business::query()->create([
            'owner_id' => $user->id,
            'name' => $validated['business_name'],
            'slug' => Business::uniqueSlug($validated['business_name']),
            'email' => $user->email,
            'phone' => $validated['phone'] ?? null,
            'status' => 'trial',
            'trial_ends_at' => now()->addDays(14),
        ]);

        $business->users()->attach($user->id, [
            'role' => 'owner',
            'title' => 'Business Owner',
            'status' => 'active',
            'joined_at' => now(),
        ]);

        $logger->log($user, 'auth.registered_business', 'Registered a new business account.', $business, [], $request);

        session()->put('current_business_id', $business->id);

        return redirect()->route('auth.choose-plan');
    }
}
