/*
 * Copyright (C) 2026  Tim Zimmermann <tim@aglais.org>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package org.aglais.zms.server.route;

import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpRequest;
import org.aglais.zms.db.core.Database;
import org.aglais.zms.server.routing.HttpMethod;
import org.aglais.zms.server.routing.HttpRoute;

import static org.aglais.zms.api.core.APIConstants.*;
import static org.aglais.zms.server.route.util.RouteUtil.readJson;
import static org.aglais.zms.server.route.util.RouteUtil.writeJson;

/**
 * Route handler for administrative endpoints under /db/
 */
public class DbAdminRoute {

    private final Database db;

    /**
     * Create a new database admin route handler
     *
     * @param db The {@link Database} to operate on
     */
    public DbAdminRoute(Database db) {
        this.db = db;
    }

    @HttpRoute(path = URL_DB_VERSION)
    public void dbVersion(ChannelHandlerContext ctx, HttpRequest request, FullHttpResponse response) {
        writeJson(response.content(), db.getVersion());
    }

    @HttpRoute(path = URL_DB_REQUIRED_VERSION)
    public void dbRequiredVersion(ChannelHandlerContext ctx, HttpRequest request, FullHttpResponse response) {
        writeJson(response.content(), db.getRequiredVersion());
    }

    @HttpRoute(path = URL_DB_UPGRADE, method = HttpMethod.POST)
    public void dbUpgrade(ChannelHandlerContext ctx, HttpRequest request, FullHttpResponse response) {
        writeJson(response.content(), db.upgrade(readJson(request, Integer.class)));
    }

}
