<?php

namespace App\Http\Controllers;

use App\Models\User;
use App\Support\MagicLoginException;
use App\Support\MagicLoginService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;

class AuthController extends Controller
{
    public function login(Request $request): JsonResponse
    {
        $validated = $request->validate([
            'email' => ['required', 'email'],
            'password' => ['required', 'string'],
        ]);

        $user = User::query()->where('email', $validated['email'])->first();

        if (! $user || ! Hash::check($validated['password'], $user->password)) {
            return response()->json([
                'message' => 'Invalid credentials.',
            ], 422);
        }

        return response()->json([
            'token' => $user->createToken('admin-dashboard')->plainTextToken,
            'user' => $user->only('id', 'name', 'email', 'role', 'team'),
        ]);
    }

    public function me(Request $request): JsonResponse
    {
        return response()->json([
            'user' => $request->user()?->only('id', 'name', 'email', 'role', 'team'),
        ]);
    }

    public function redeemMagicLogin(Request $request, MagicLoginService $magicLogin): JsonResponse
    {
        $validated = $request->validate([
            'token' => ['required', 'string'],
        ]);

        try {
            $payload = $magicLogin->validateToken($validated['token']);
        } catch (MagicLoginException $exception) {
            return response()->json([
                'message' => $exception->getMessage(),
            ], $exception->status());
        }

        $user = User::query()->where('email', $payload['email'])->first();

        if (! $user) {
            return response()->json([
                'message' => 'The magic login user no longer exists.',
            ], 422);
        }

        try {
            $magicLogin->consumeToken($validated['token'], $payload['exp']);
        } catch (MagicLoginException $exception) {
            return response()->json([
                'message' => $exception->getMessage(),
            ], $exception->status());
        }

        return response()->json([
            'token' => $user->createToken('admin-dashboard')->plainTextToken,
            'user' => $user->only('id', 'name', 'email', 'role', 'team'),
        ]);
    }

    public function logout(Request $request): JsonResponse
    {
        $request->user()?->currentAccessToken()?->delete();

        return response()->json([
            'message' => 'Logged out.',
        ]);
    }
}
