<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Affiliate;
use App\Models\Setting;
use App\Models\User;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Password;
use Illuminate\Validation\Rules\Password as PasswordRule;

class AuthController extends Controller
{
    public function register(Request $request): JsonResponse
    {
        if (!Setting::get('registration_enabled', true)) {
            return response()->json(['message' => 'New registrations are currently disabled.'], 403);
        }

        $data = $request->validate([
            'username' => 'required|string|min:3|max:30|unique:users,username',
            'email'    => 'required|email|unique:users,email',
            'password' => ['required', 'confirmed', PasswordRule::min(6)],
            'referral_code' => 'nullable|string|exists:affiliates,code',
        ]);

        $affiliate = !empty($data['referral_code'])
            ? Affiliate::where('code', $data['referral_code'])->where('status', 'active')->first()
            : null;

        $welcomeBalance = Setting::get('welcome_balance_enabled', true)
            ? (float) Setting::get('welcome_balance', 500.00)
            : 0.00;

        $user = User::create([
            'name'     => $data['username'],
            'username' => $data['username'],
            'email'    => $data['email'],
            'password' => Hash::make($data['password']),
            'balance'  => $welcomeBalance,
            'affiliate_id' => $affiliate?->id,
            'referral_code' => $affiliate?->code,
        ]);

        $user->assignRole('player');

        $token = $user->createToken('auth_token')->plainTextToken;

        return response()->json([
            'user'  => $this->formatUser($user),
            'token' => $token,
        ], 201);
    }

    public function login(Request $request): JsonResponse
    {
        $data = $request->validate([
            'email'    => 'required|email',
            'password' => 'required|string',
        ]);

        if (!Auth::attempt(['email' => $data['email'], 'password' => $data['password']])) {
            return response()->json(['message' => 'Invalid credentials.'], 401);
        }

        $user = Auth::user();

        if (!$user->is_active) {
            Auth::logout();
            return response()->json(['message' => 'Account is suspended.'], 403);
        }

        $user->tokens()->delete();
        $token = $user->createToken('auth_token')->plainTextToken;

        return response()->json([
            'user'  => $this->formatUser($user),
            'token' => $token,
        ]);
    }

    public function logout(Request $request): JsonResponse
    {
        $request->user()->currentAccessToken()->delete();
        return response()->json(['message' => 'Logged out successfully.']);
    }

    public function me(Request $request): JsonResponse
    {
        return response()->json(['user' => $this->formatUser($request->user())]);
    }

    public function forgotPassword(Request $request): JsonResponse
    {
        $request->validate(['email' => 'required|email']);

        $status = Password::sendResetLink($request->only('email'));

        return $status === Password::RESET_LINK_SENT
            ? response()->json(['message' => 'Reset link sent to your email.'])
            : response()->json(['message' => 'Email not found.'], 404);
    }

    public function resetPassword(Request $request): JsonResponse
    {
        $request->validate([
            'token'    => 'required',
            'email'    => 'required|email',
            'password' => ['required', 'confirmed', PasswordRule::min(6)],
        ]);

        $status = Password::reset(
            $request->only('email', 'password', 'password_confirmation', 'token'),
            function (User $user, string $password) {
                $user->forceFill(['password' => Hash::make($password)])->save();
                $user->tokens()->delete();
            }
        );

        return $status === Password::PASSWORD_RESET
            ? response()->json(['message' => 'Password reset successfully.'])
            : response()->json(['message' => 'Invalid or expired token.'], 422);
    }

    private function formatUser(User $user): array
    {
        return [
            'id'                   => $user->id,
            'name'                 => $user->name,
            'username'             => $user->username,
            'email'                => $user->email,
            'avatar'               => $user->avatar,
            'balance'              => (float) $user->balance,
            'vip_tier'             => $user->vip_tier,
            'vip_points'           => $user->vip_points,
            'roles'                => $user->getRoleNames(),
            'email_notifications'  => $user->email_notifications,
            'promotional_offers'   => $user->promotional_offers,
            'security_alerts'      => $user->security_alerts,
            'is_active'            => $user->is_active,
            'email_verified_at'    => $user->email_verified_at,
            'created_at'           => $user->created_at,
        ];
    }
}
