<?php

declare(strict_types=1);

namespace App\Http\Controllers\User;

use App\Http\Controllers\Controller;
use App\Services\OtpService;
use App\Services\UserService;
use App\Support\ApiResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class AuthenticateController extends Controller
{
    public function __invoke(Request $request, OtpService $otpService, UserService $userService)
    {
        $validator = Validator::make($request->all(), [
            'cellphone' => 'required|starts_with:09',
            'password' => 'required_without:code|max:255',
            'code' => 'required_without:password|numeric',
        ]);
        if ($validator->fails()) {
            return ApiResponse::response(errors: $validator->errors(), status: 422);
        }

        if ($request->code) {
            $validator = Validator::make($request->all(), [
                'code' => 'required|numeric',
            ]);
            if ($validator->fails()) {
                return ApiResponse::response(errors: $validator->errors(), status: 422);
            }

            $checkHashCode = $otpService->checkOtp($request->cellphone, $request->code);
            if (! $checkHashCode) {
                return ApiResponse::response(message: 'کد وارد شده صحیح نیست', status: 409);
            }
        }

        return $userService->authenticate($request);
    }
}
