<?php

namespace App\Http\Controllers;

use App\Models\User;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\ValidationException;

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

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

        if (! $user || ! Hash::check($request->password, $user->password)) {
            throw ValidationException::withMessages([
                'message' => 'Грешен имейл или парола.',
            ]);
        }

        if (! $user->active) {
            throw ValidationException::withMessages([
                'message' => 'Акаунтът е деактивиран.',
            ]);
        }

        if (! $user->isAdmin() && ! $user->isOperator()) {
            throw ValidationException::withMessages([
                'message' => 'Нямате достъп до тази система.',
            ]);
        }

        // Clean up tokens unused for 7+ days so old sessions don't pile up,
        // but keep all recent ones so multi-device usage (phone + tablet) works.
        $user->tokens()
            ->where('name', 'control-panel')
            ->where(function ($q) {
                $q->where('last_used_at', '<', now()->subDays(7))
                  ->orWhere(fn ($q2) => $q2->whereNull('last_used_at')
                      ->where('created_at', '<', now()->subDays(7)));
            })
            ->delete();

        $token = $user->createToken('control-panel', ['*'], now()->addDays(7))->plainTextToken;

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

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

        return response()->json(['message' => 'Успешен изход.']);
    }

    public function me(Request $request): JsonResponse
    {
        $user = $request->user();

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