<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Http\Requests\Api\RegisterRequest;
use App\Models\User;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Hash;

class AuthController extends Controller
{
    public function register(RegisterRequest $request): JsonResponse
    {
        if (!config('app.allow_registration')) {
            return response()->json([
                'error' => ['code' => 'registration_disabled', 'message' => 'Registration is currently disabled.'],
            ], 403);
        }

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

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

        return response()->json([
            'token' => $token,
            'user' => ['id' => $user->id, 'email' => $user->email, 'name' => $user->name],
        ], 201);
    }

    public function login(\App\Http\Requests\Api\LoginRequest $request): JsonResponse
    {
        $user = User::where('email', $request->string('email'))->first();

        if (!$user || !Hash::check($request->string('password'), $user->password)) {
            return response()->json([
                'error' => ['code' => 'invalid_credentials', 'message' => 'Email or password is incorrect.'],
            ], 422);
        }

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

        return response()->json([
            'token' => $token,
            'user' => ['id' => $user->id, 'email' => $user->email, 'name' => $user->name],
        ]);
    }

    public function me(\Illuminate\Http\Request $request): JsonResponse
    {
        $user = $request->user();
        return response()->json([
            'id' => $user->id,
            'email' => $user->email,
            'name' => $user->name,
        ]);
    }

    public function logout(\Illuminate\Http\Request $request): JsonResponse
    {
        $request->user()->currentAccessToken()->delete();
        return response()->json(['ok' => true]);
    }
}
