<?php

namespace App\Http\Modules\User;

use Auth;
use App\Models\User;
use App\Http\Rules\User\LoginRule;

use App\Http\Helpers\General;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\DB;

class LoginModule
{
    public function __construct()
    {
        
    }

    public static function login(Request $request)
    {
        $validation = LoginModule::validation($request, '', 'LOGIN');
        if (!$validation->status) {
            return response()->json($validation, 422);
        }

        $email = $request->input('email');

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

        $token = $user->createToken($user->id, ['only-user']);
        $data = General::returnTokenData($user, $token->accessToken, true);
        return response()->json($data);
    }

    private static function validation(Request $request, $id = '', $method = 'POST')
    {
        $data = $request->all();

        $rule= [];
        if ($method == 'LOGIN') {
            $rule = [
                'email' => ['required', new LoginRule('manual', $data['password'] ?? '')],
                'password' => ['required']
            ];
        }

        $validator = Validator::make($data, $rule, config('error_code'));

        $errors = $validator->errors();

        if ($validator->fails()) {
            $data = General::returnErrorData($errors);
            return $data;
        }
        else {
            return (object)['status' => true];
        }
    } 
}
