<?php

namespace App\Http\Controllers\Api\V1;

use App\Http\Controllers\Controller;
use App\Http\Requests\Api\LoginRequest;
use App\Http\Requests\Api\RegisterRequest;
use App\Http\Resources\Api\UserResource;
use App\Services\ActivityLogService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use App\Models\User;

class AuthController extends Controller
{
    public function register(RegisterRequest $request): JsonResponse
    {
        $user = User::create([
            'name' => $request->validated('name'),
            'email' => $request->validated('email'),
            'password' => Hash::make($request->validated('password')),
            'phone' => $request->validated('phone'),
            'role' => $request->validated('role'),
        ]);

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

        return response()->json([
            'data' => [
                'user' => new UserResource($user),
                'token' => $token,
                'token_type' => 'Bearer',
            ],
            'message' => __('Registration successful.'),
        ], 201);
    }

    public function login(LoginRequest $request): JsonResponse
    {
        if (! Auth::attempt($request->only('email', 'password'))) {
            return response()->json([
                'message' => __('Invalid credentials.'),
            ], 401);
        }

        $user = User::where('email', $request->validated('email'))->firstOrFail();

        if (! $user->is_active) {
            Auth::logout();

            return response()->json([
                'message' => __('Account is disabled.'),
            ], 403);
        }

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

        ActivityLogService::log(
            'login',
            null,
            ['email' => $user->email, 'role' => $user->role],
            "Connexion de {$user->name} ({$user->email})",
            $user->id,
            $request
        );

        return response()->json([
            'data' => [
                'user' => new UserResource($user),
                'token' => $token,
                'token_type' => 'Bearer',
            ],
            'message' => __('Login successful.'),
        ]);
    }

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

        ActivityLogService::log(
            'logout',
            null,
            ['email' => $user->email],
            "Déconnexion de {$user->name}",
            $user->id,
            $request
        );

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

    public function user(Request $request): JsonResponse
    {
        return response()->json([
            'data' => new UserResource($request->user()),
        ]);
    }

    public function update(Request $request): JsonResponse
    {
        $user = $request->user();
        $validated = $request->validate([
            'name' => ['sometimes', 'string', 'max:255'],
            'phone' => ['sometimes', 'nullable', 'string', 'max:20'],
        ]);

        $user->update($validated);

        return response()->json([
            'data' => new UserResource($user->fresh()),
            'message' => __('Profile updated successfully.'),
        ]);
    }

    public function updatePassword(Request $request): JsonResponse
    {
        $validated = $request->validate([
            'password' => ['required', 'string', 'min:8', 'confirmed'],
        ]);

        $request->user()->update([
            'password' => Hash::make($validated['password']),
        ]);

        return response()->json([
            'message' => __('Password updated successfully.'),
        ]);
    }
}
