<?php

namespace App\DBRealTestSupport\TransactionSupported\Session;

use Illuminate\Support\Facades\DB;
use App\DBRealTestSupport\TableCreation as TC;
use App\DBRealTestSupport\TransactionSupported\Session\TSAdminMother;

class TSAdminSessionMother
{

    public static function buildRandom($idAdmin = null, $id = 1)
    {
        return [
            'Id_AdminSession'           => $id,
            'AdminSession_IP'           => '127.0.0.1',
            'AdminSession_DateStart'    => date('Y-m-d H:i:s'),
            'AdminSession_DateEnd'      => date('Y-m-d H:i:s', strtotime('+1 day')),
            'AdminSession_Token'        => '',
            'AdminSession_Status'       => 2,
            'Id_Admin'                  => $idAdmin ?? TSAdminMother::pushRandom()['Id_Admin'],
        ];
    }

    public static function pushRandom($idAdmin, $id = 1)
    {
        return self::push(self::buildRandom($idAdmin, $id));
    }

    private static function push($object)
    {
        $token = 'SY-0' . sha1(date('Y-m-d H:i:s') . $object['Id_Admin']) . "0-OWN";
        DB::insert(
            "INSERT INTO `t_admin_session` 
            (
                `AdminSession_IP`,
                `AdminSession_DateStart`,
                `AdminSession_DateEnd`,
                `AdminSession_Token`,
                `AdminSession_Status`,
                `Id_Admin`
            ) VALUES (?,?,?,?,?,?)",
            [
                $object['AdminSession_IP'],
                $object['AdminSession_DateStart'],
                $object['AdminSession_DateEnd'],
                $token,
                $object['AdminSession_Status'],
                $object['Id_Admin']
            ]
        );
        $object['AdminSession_Token'] = $token;
        $object['Id_AdminSession'] = DB::select('SELECT LAST_INSERT_ID() as `Id`')[0]->Id;
        return $object;
    }

    public static function clear()
    {
        TC::clearTables(
            ...array_merge(
                // LanguageMother::clear(),
                TSAdminRoleMother::tablesToClear(),
                [
                    TC::TYPE_DOCUMENT,
                    TC::TYPE_DOCUMENT_TRANSL,
                    TC::COUNTRY,
                    TC::STATE,
                    TC::CITY,
                    TC::ADMIN,
                    TC::ADMIN_SESSION,
                    TC::CREDENTIAL
                ]
            )
        );
        TSCredentialGenerator::clear();
    }
}
