<?php

namespace App\Http\Controllers\v1\Tenancy\Auth;

use App\Http\Controllers\Controller;
use App\Models\Tenancy\PhoneConfirmation;
use Illuminate\Http\Response;
use Illuminate\Support\Carbon;

class VerifyPhoneController extends Controller
{
    public function __invoke(string $phone, int $code): Response
    {
        $now = Carbon::now();
        $confirmation = PhoneConfirmation::where('phone', $phone)
            ->where('code', $code)
            ->where('is_confirmed', false)
            ->where('expires_at', '>=', $now->toDateTimeString())
            ->where('created_at', '<=', $now->toDateTimeString())
            ->first();
        if (! $confirmation) {
            return $this->error('Wrong Code', 517);
        }
        $confirmation->is_confirmed = true;
        $confirmation->save();

        return $this->ok(['success' => 'Phone confirmed']);
    }
}
