<?php

declare(strict_types=1);

namespace App\Http\Controllers;

use App\Domain\Plugin\PluginManager;
use App\Models\Category;
use App\Models\User;
use App\Settings\GeneralSettings;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\View\View;
use Plugins\Larablog\Membership\Domain\MembershipService;
use Spatie\Permission\Models\Role;

class AuthController extends Controller
{
    public function showLogin(GeneralSettings $settings): View
    {
        return view('theme::login', [
            'settings' => $settings,
            'categories' => Category::query()->orderBy('display_order')->get(),
            'seo' => ['title' => '登录 - '.$settings->site_name],
        ]);
    }

    public function showRegister(GeneralSettings $settings): View
    {
        return view('theme::register', [
            'settings' => $settings,
            'categories' => Category::query()->orderBy('display_order')->get(),
            'seo' => ['title' => '注册 - '.$settings->site_name],
        ]);
    }

    public function showProfile(GeneralSettings $settings): View|RedirectResponse
    {
        if (! Auth::check()) {
            return redirect('/login.shtml');
        }

        $membership = null;
        try {
            if (class_exists(MembershipService::class)
                && app(PluginManager::class)->isEnabled('larablog/membership')) {
                $membership = app(MembershipService::class)
                    ->statusFor(Auth::user());
            }
        } catch (\Throwable) {
            $membership = null;
        }

        return view('theme::profile', [
            'user' => Auth::user(),
            'settings' => $settings,
            'categories' => Category::query()->orderBy('display_order')->get(),
            'membership' => $membership,
            'seo' => ['title' => '资料 - '.$settings->site_name],
        ]);
    }

    public function login(Request $request): RedirectResponse
    {
        $key = 'login:'.$request->ip();
        if (RateLimiter::tooManyAttempts($key, 10)) {
            abort(429, 'Too many login attempts.');
        }
        RateLimiter::hit($key, 60);

        $data = $request->validate([
            'login' => ['required', 'string', 'max:120'],
            'password' => ['required', 'string', 'max:120'],
        ]);

        if (! Auth::attempt(['login' => $data['login'], 'password' => $data['password']], $request->boolean('remember'))) {
            return back()->withErrors(['login' => '用户名或密码错误'])->withInput($request->only('login'));
        }

        $request->session()->regenerate();

        /** @var User $user */
        $user = Auth::user();
        $user->forceFill([
            'login_count' => ((int) $user->login_count) + 1,
            'login_ip' => $request->ip(),
            'login_at' => now(),
        ])->save();

        return redirect()->intended('/')->with('status', '登录成功');
    }

    public function register(Request $request): RedirectResponse
    {
        $key = 'register:'.$request->ip();
        if (RateLimiter::tooManyAttempts($key, 5)) {
            abort(429, 'Too many registration attempts.');
        }
        RateLimiter::hit($key, 3600);

        $data = $request->validate([
            'username' => ['required', 'string', 'min:3', 'max:40', 'alpha_dash', 'unique:users,username'],
            'email' => ['nullable', 'email', 'max:120', 'unique:users,email'],
            'password' => ['required', 'string', 'min:6', 'max:120', 'confirmed'],
            'url' => ['nullable', 'url', 'max:255'],
        ]);

        Role::findOrCreate('member');

        $user = User::query()->create([
            'name' => $data['username'],
            'username' => $data['username'],
            'email' => $data['email'] ?? null,
            'password' => $data['password'],
            'url' => $data['url'] ?? null,
            'reg_ip' => $request->ip(),
        ]);
        $user->assignRole('member');

        Auth::login($user);
        $request->session()->regenerate();

        return redirect('/')->with('status', '注册成功');
    }

    public function updateProfile(Request $request): RedirectResponse
    {
        /** @var User $user */
        $user = Auth::user();
        abort_unless($user !== null, 403);

        $data = $request->validate([
            'url' => ['nullable', 'url', 'max:255'],
            'email' => ['nullable', 'email', 'max:120', 'unique:users,email,'.$user->id],
            'password' => ['nullable', 'string', 'min:6', 'max:120', 'confirmed'],
        ]);

        $user->url = $data['url'] ?? null;
        $user->email = $data['email'] ?? null;
        if (! empty($data['password'])) {
            $user->password = $data['password'];
            $user->password_legacy = null;
        }
        $user->save();

        return back()->with('status', '资料已更新');
    }

    public function logout(Request $request): RedirectResponse
    {
        Auth::logout();
        $request->session()->invalidate();
        $request->session()->regenerateToken();

        return redirect('/')->with('status', '已退出登录');
    }
}
