/*******************************************************************************
 * Copyright (c) 2025, Jan Koester jan.koester@gmx.net
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 * Redistributions of source code must retain the above copyright
 *      notice, this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 *      notice, this list of conditions and the following disclaimer in the
 *      documentation and/or other materials provided with the distribution.
 * Neither the name of the <organization> nor the
 *      names of its contributors may be used to endorse or promote products
 *      derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *******************************************************************************/

#include <chrono>
#include <thread>

#include "backends/file.h"
#include "backends/cluster.h"

#include "backend.h"
#include "authdb.h"

authdb::AuthBackend::AuthBackend(int type, const std::string &options,const std::string &domain) : _Type(type),_Options(options),_Domain(domain) {
    _Type=type;
    if(_Type==AuthBackendType::File){
        _Api =  new class File(_Options.c_str(),VERSION,_Domain.c_str());
    }else if(_Type==AuthBackendType::ClusterStore){
        _Api = new class ClusterBackend(_Domain.c_str(),VERSION,_Options.c_str());
    }else{
        throw AuthBackendError("unkown file backend");
    }
}

authdb::AuthBackend::AuthBackend(const AuthBackend &backend){
     _Type=backend._Type;
    if(_Type==AuthBackendType::File){
        _Api = new class File(backend._Options.c_str(),VERSION,backend._Domain.c_str());
    }else if(_Type==AuthBackendType::ClusterStore){
        _Api = new class ClusterBackend(backend._Domain.c_str(),VERSION,backend._Options.c_str());
    }
}

authdb::AuthBackend::~AuthBackend(){
        if(_Type==AuthBackendType::File){
            delete (class File*) _Api;
        }else if(_Type==AuthBackendType::ClusterStore){
            delete (class ClusterBackend*) _Api;
        }
}

void authdb::AuthBackend::read(char unsigned *src,size_t srcsize){
   _Api->read(src,srcsize);
}

void authdb::AuthBackend::write(const unsigned char* dest, size_t destsize){
   _Api->write(dest,destsize);
}

void authdb::AuthBackend::lock(){
    // Prefetch cluster data BEFORE acquiring the exclusive lock.
    // This avoids blocking all other threads while waiting for network I/O.
    _Api->prefetch();
    _Lock.lock();
    try {
        _Api->lock();
    } catch (...) {
        _Lock.unlock();
        throw;
    }
}

void authdb::AuthBackend::unlock(){
    _Api->unlock();
    _Lock.unlock();
}

void authdb::AuthBackend::lock_shared(){
    _Api->prefetch();
    _Lock.lock_shared();
}

void authdb::AuthBackend::unlock_shared(){
    _Lock.unlock_shared();
}

void authdb::AuthBackend::setPos(size_t pos){
    _Api->setPos(pos);
}

size_t authdb::AuthBackend::getPos(){
    return _Api->getPos();
}


size_t authdb::AuthBackend::end(){
    return _Api->end();
}

size_t authdb::AuthBackend::getRevesion(){
    return _Api->getRevesion();
}

void authdb::AuthBackend::newRevesion(){
    _Api->newRevesion();
}

void authdb::AuthBackend::vacuum(){
    _Api->vacuum();
}

void authdb::AuthBackend::vacuum(size_t &sizeBefore, size_t &sizeAfter){
    Guard guard(*this);
    sizeBefore = _Api->end();
    _Api->vacuum();
    sizeAfter = _Api->end();
}

void authdb::AuthBackend::purge(){
    _Api->purge();
}

void authdb::AuthBackend::flushSync(){
    _Api->flushSync();
}

bool authdb::AuthBackend::clusterDataExists() const {
    return _Api->clusterDataExists();
}

static thread_local authdb::AuthBackend* _guard_locked_backend = nullptr;
static thread_local authdb::AuthBackend::LockMode _guard_locked_mode;

authdb::AuthBackend::Guard::Guard(AuthBackend &backend, LockMode mode) : _Backend(backend), _Mode(mode), _Owns(false), _Upgraded(false){
    if(_guard_locked_backend == &backend){
        if(mode == Exclusive && _guard_locked_mode == Shared){
            _Backend.unlock_shared();
            _Backend.lock();
            _guard_locked_mode = Exclusive;
            _Upgraded = true;
        }
    } else {
        if(_Mode == Exclusive)
            _Backend.lock();
        else
            _Backend.lock_shared();
        _guard_locked_backend = &backend;
        _guard_locked_mode = mode;
        _Owns = true;
    }
}

authdb::AuthBackend::Guard::~Guard(){
    if(_Upgraded){
        _Backend.unlock();
        _Backend.lock_shared();
        _guard_locked_mode = Shared;
    } else if(_Owns){
        if(_Mode == Exclusive)
            _Backend.unlock();
        else
            _Backend.unlock_shared();
        _guard_locked_backend = nullptr;
    }
}

int authdb::AuthBackend::searchValue(const char *fieldname, const char *value){
    Guard guard(*this, Shared);
    authdb::AuthData::Record *user=new AuthData::Record;
    size_t rd=sizeof(authdb::AuthHeader),brd=rd;
    while(rd<end()){
        setPos(rd);
        read((unsigned char*)user,sizeof(AuthData::Record));
        rd=getPos()+user->datasize;
        if(strcmp(user->fieldname,fieldname) == 0){
            user->data = new char[user->datasize];
            read((unsigned char*)user->data,user->datasize);
            if(strcmp(user->data,value) == 0){
                delete[] user->data;
                user->data=nullptr;
                goto VALUEFOUND;
            }
            delete[] user->data;
            user->data=nullptr;
        }
        brd=rd;
    }
VALUEFOUND:
    delete user;
    return brd;
}
