<?php

namespace Tests\Support\Auth;

use App\Models\EmailOtpModel;
use App\Models\UserModel;
use Config\Tieasy;

trait AuthTestTrait
{
    protected function createUser(string $email, int $onboardingComplete = 0, int $active = 1): array
    {
        $users = new UserModel();
        $id    = $users->insert([
            'email'                        => strtolower(trim($email)),
            'profile_onboarding_completed' => $onboardingComplete,
            'is_active'                    => $active,
            'last_login_at'                => null,
        ], true);

        $user = $users->find($id);
        $this->assertIsArray($user);

        return $user;
    }

    protected function latestOtpRow(string $email): ?array
    {
        $row = (new EmailOtpModel())->builder()
            ->where('email', strtolower(trim($email)))
            ->orderBy('id', 'DESC')
            ->limit(1)
            ->get()
            ->getRowArray();

        return $row === null ? null : $row;
    }

    protected function backdateLatestOtp(string $email, int $createdAgoSeconds, ?int $expiresAgoSeconds = null): void
    {
        $row = $this->latestOtpRow($email);
        $this->assertNotNull($row);

        $update = [
            'created_at' => date('Y-m-d H:i:s', time() - $createdAgoSeconds),
        ];

        if ($expiresAgoSeconds !== null) {
            $update['expires_at'] = date('Y-m-d H:i:s', time() - $expiresAgoSeconds);
        }

        db_connect()->table('email_otps')->where('id', $row['id'])->update($update);
    }

    protected function rememberCookieName(): string
    {
        return (new Tieasy())->rememberCookie;
    }

    protected function putRequestCookie(string $name, string $value): void
    {
        $_COOKIE[$name] = $value;
        $request        = service('request');
        $cookies        = $request->fetchGlobal('cookie') ?? [];
        if (! is_array($cookies)) {
            $cookies = [];
        }
        $cookies[$name] = $value;
        $request->setGlobal('cookie', $cookies);
    }

    protected function readResponseCookie(string $name): ?string
    {
        $cookie = service('response')->getCookie($name);
        if ($cookie === null) {
            return null;
        }

        $value = $cookie->getValue();

        return $value === '' ? null : $value;
    }
}
