<?php

namespace App\Http\Controllers;

use App\Models\User;
use Illuminate\Support\Str;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use App\Http\Validation\LoginValidation;
use Illuminate\Support\Facades\Validator;

class AuthenticationController extends Controller
{
    public function register(Request $request) {
        $user = User::create([
            'identifyer' => $request->input('identifyer'),
            'password' => bcrypt($request->input('password')),
            'api_token' => Str::random(60)
        ]);

        return response()->json($user);
    }

    public function login(Request $request, LoginValidation $validation) {
        
        $validator = Validator::make($request->all(), $validation->rules(), $validation->messages());
        if($validator->fails()){
            return response()->json(['errors' => $validator->errors()],401);
        }
        
        if(Auth::attempt([
            'identifyer' => $request->input('identifyer'),
            'password' => $request->input('password')])){
            $user = User::where('identifyer',$request->input('identifyer'))->firstOrFail();
            return response()->json($user);
        } else {
            return response()->json(['errors' => 'bad_pwd'],401);
        };
    }
}
