<?php

namespace App\Domains\Auth\Controllers;

use App\Domains\Auth\Requests\AdminAppLoginRequest;
use App\Domains\Auth\Resources\UserResource;
use App\Domains\Auth\Services\PasswordLoginService;
use App\Http\Controllers\Controller;
use Illuminate\Http\JsonResponse;

class AdminAppLoginController extends Controller
{
    public function __construct(
        private readonly PasswordLoginService $passwordLoginService,
    ) {}

    public function __invoke(AdminAppLoginRequest $request): JsonResponse
    {
        $credentials = $request->validated();
        $user = $this->passwordLoginService->authenticateAdminApp(
            $credentials['email'],
            $credentials['password'],
            $request->ip(),
            $request->userAgent(),
        );

        $expirationMinutes = (int) config('sanctum.expiration');
        $token = $user->createToken(
            'adminapp-token',
            ['adminapp'],
            now()->addMinutes($expirationMinutes),
        )->plainTextToken;

        return response()->json([
            'code' => 'auth.login_success',
            'message' => __('api.auth.login_success'),
            'token' => $token,
            'token_type' => 'Bearer',
            'user' => UserResource::make($user),
        ]);
    }
}
