#include "fesa/core/status.hpp"

#include <gtest/gtest.h>

#include <filesystem>
#include <stdexcept>
#include <string>
#include <utility>
#include <vector>

namespace {

fesa::Diagnostic modelDiagnostic() {
    return fesa::Diagnostic{
        fesa::Severity::error,
        "invalid-beam-length",
        {std::filesystem::path{"beam.inp"}, 12U},
        "*ELEMENT",
        "Beam-1.10",
        "Beam length must be positive."};
}

} // namespace

TEST(CoreDiagnostics, ResultEnforcesValueErrorExclusivity) {
    const fesa::Status ok = fesa::Status::ok();
    EXPECT_TRUE(ok.isOk());
    EXPECT_FALSE(ok.failureCategory().has_value());
    EXPECT_TRUE(ok.diagnostics().empty());

    const fesa::Status uncategorized =
        fesa::Status::failure(std::vector<fesa::Diagnostic>{modelDiagnostic()});
    EXPECT_FALSE(uncategorized.isOk());
    EXPECT_FALSE(uncategorized.failureCategory().has_value());
    ASSERT_EQ(uncategorized.diagnostics().size(), 1U);
    EXPECT_EQ(uncategorized.diagnostics()[0].code, "invalid-beam-length");

    const fesa::Status categorized = fesa::Status::failure(
        fesa::FailureCategory::model,
        std::vector<fesa::Diagnostic>{modelDiagnostic()});
    EXPECT_FALSE(categorized.isOk());
    ASSERT_TRUE(categorized.failureCategory().has_value());
    EXPECT_EQ(*categorized.failureCategory(), fesa::FailureCategory::model);

    const auto success = fesa::Result<std::string>::success("solved");
    EXPECT_TRUE(success.hasValue());
    EXPECT_TRUE(success.status().isOk());
    EXPECT_EQ(success.value(), "solved");

    auto copied = success;
    EXPECT_EQ(copied.value(), "solved");
    auto moved = std::move(copied);
    EXPECT_EQ(moved.value(), "solved");

    auto failure = fesa::Result<std::string>::failure(categorized);
    EXPECT_FALSE(failure.hasValue());
    EXPECT_FALSE(failure.status().isOk());
    EXPECT_EQ(failure.status().failureCategory(), fesa::FailureCategory::model);
    EXPECT_THROW(failure.value(), std::logic_error);

    const auto& constFailure = failure;
    EXPECT_THROW(constFailure.value(), std::logic_error);
    EXPECT_THROW(
        (void)fesa::Result<std::string>::failure(fesa::Status::ok()),
        std::invalid_argument);
}
