<?php

namespace App\Http\Controllers\Api\Auth;

use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Contracts\Foundation\Application;
use Illuminate\Contracts\Routing\ResponseFactory;
use Illuminate\Http\Response;

class AuthenticateController extends Controller
{
    /**
     * Build token to return api response
     *
     * @param User $user
     * @param int $code
     * @param string|null $message
     * @param array|null $data
     * @return Response|Application|ResponseFactory
     */
    protected function respondWithToken(User $user, int $code = 100, string $message = null, array $data = null): Response|Application|ResponseFactory
    {
        // Revoke all tokens...
        $user->tokens()->delete();

        // Create new token
        $device = $user->lastUserDevice();
        $token = $user->createToken(
            $device !== null
                ? $device->{'device_name'} . '_' . $device->{'native_device_id'}
                :  "Personal Access Token"
        );

        return api_response(
            $code,
            $message ?? 'Ok',
            $data !== null ? array_merge($data, [
                'token' => $token,
            ]) : $token,
        );
    }

    /**
     * Log out (Revoke all tokens).
     *
     * @return ResponseFactory|Response
     */
    protected function logout(): Response|ResponseFactory
    {
        /** @var User $user */
        $user = auth()->user();

        // Revoke all tokens...
        $user->tokens()->delete();

        return api_response(100, 'Ok');
    }

    /**
     * Get auth user
     *
     * @return Application|ResponseFactory|Response
     */
    protected function user(): Response|Application|ResponseFactory
    {
        /** @var User $user */
        $user = auth()->user();

        return api_response(100, 'Ok',  self::responseWithUser($user));
    }

    /**
     * Response with user data
     *
     * @param User $user
     * @return User
     */
    public static function responseWithUser(User $user): User
    {
        return $user->load([
            'userDetail',
            'country',
            'wallet.currency',
            'business.businessCategory'
        ]);
    }
}
