<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\Rules\Password;
use Illuminate\Validation\ValidationException;

class SanctumAuthController extends Controller
{
    /**
     * Register a new user and return a token
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function register(Request $request)
    {
        try {
            $request->validate([
                'email' => ['required', 'string', 'email', 'max:255', 'unique:users'],
                'password' => ['required', 'confirmed', Password::defaults()],
            ]);

            $user = User::create([
                'email' => $request->email,
                'password' => Hash::make($request->password),
            ]);

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

            return response()->json([
                'success' => [
                    'data' => [
                        'token' => $token,
                        'user' => $user,
                    ],
                    'message' => 'Registration completed successfully.',
                ],
            ], 201);
        } catch (ValidationException $e) {
            return response()->json([
                'error' => [
                    'data' => $e->errors(),
                    'message' => 'Please review your inputs before submitting again.',
                ],
            ], 422);
        } catch (\Exception $e) {
            return response()->json([
                'error' => [
                    'data' => [],
                    'message' => $e->getMessage(),
                ],
            ], 500);
        }
    }

    /**
     * Login a user and return a token
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function login(Request $request)
    {
        try {
            $request->validate([
                'email' => ['required', 'string', 'email'],
                'password' => ['required', 'string'],
            ]);

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

            $user = User::where('email', $request->email)->firstOrFail();
            $token = $user->createToken('auth_token')->plainTextToken;

            return response()->json([
                'success' => [
                    'data' => [
                        'token' => $token,
                        'user' => $user,
                    ],
                    'message' => 'Authentication successful.',
                ],
            ]);
        } catch (ValidationException $e) {
            return response()->json([
                'error' => [
                    'data' => $e->errors(),
                    'message' => 'Please review your inputs before submitting again.',
                ],
            ], 422);
        } catch (\Exception $e) {
            return response()->json([
                'error' => [
                    'data' => [],
                    'message' => $e->getMessage(),
                ],
            ], 500);
        }
    }

    /**
     * Logout the user (revoke the token)
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function logout(Request $request)
    {
        try {
            $request->user()->currentAccessToken()->delete();

            return response()->json([
                'success' => [
                    'data' => [],
                    'message' => 'Successfully signed out.',
                ],
            ]);
        } catch (\Exception $e) {
            return response()->json([
                'error' => [
                    'data' => [],
                    'message' => $e->getMessage(),
                ],
            ], 500);
        }
    }
}
