// Copyright 2025 Bloomberg Finance L.P
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#ifndef INCLUDED_BUILDBOXCOMMON_JOBSERVER
#define INCLUDED_BUILDBOXCOMMON_JOBSERVER

#include <buildboxcommon_fileutils.h>

namespace buildboxcommon {

class JobServerClient final {
  public:
    JobServerClient(buildboxcommon::FileDescriptor readFD,
                    buildboxcommon::FileDescriptor writeFD)
        : d_readFD(std::move(readFD)), d_writeFD(std::move(writeFD))
    {
    }
    ~JobServerClient();

    // Rule of Five: Delete copy constructor and copy assignment operator
    JobServerClient(const JobServerClient &) = delete;
    JobServerClient &operator=(const JobServerClient &) = delete;

    // Rule of Five: Delete move constructor and move assignment operator
    JobServerClient(JobServerClient &&other) = delete;
    JobServerClient &operator=(JobServerClient &&other) = delete;

    static std::optional<JobServerClient> tryCreate();

    bool acquireSlot();
    bool releaseSlot();

  private:
    buildboxcommon::FileDescriptor d_readFD, d_writeFD;
    int d_slotsAcquired = 0;
};

} // namespace buildboxcommon

#endif
