<?php

namespace App\Http\Controllers\Api;

use App\Enums\SMSEnums;
use App\Http\Controllers\Controller;
use App\Http\Requests\ApiLoginRequest;
use App\Http\Resources\UserResource;
use App\Http\Services\SMSService;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Log;

class AuthController extends Controller
{
    public function login(ApiLoginRequest $request) {
        $user = User::query()
            ->where('country_id', $request->input('country_id', DefaultCountryId()))
            ->where('phone' , $request->input('phone'))
            ->first();

        if( !$user || ! Hash::check($request->input('password'), $user->password) ) {
            return ValidationError(trans('global.phone_or_password_not_correct'));
        }

        if( !$user->is_active ) {
            return ValidationError(trans('global.not_active_account'));
        }

        if(is_null($user->phone_verified_at)) {
            $user->sms()->where('type', SMSEnums::Activation)->update(['code'=>null]);
            (new SMSService($user))->sendActivationCode($user);
        }

        $device_name    =   $request->input('device_name') ?: $user->id;

        return response()->json([
            'user'   =>  new UserResource($user),
            'token' =>  $user->createToken($device_name)->plainTextToken,
        ]);
    }

    public function logout(Request $request){
        $request->user()->currentAccessToken()->delete();
        return response(null, 201);
    }
}
