package su.xserver.iikocon;

import io.vertx.core.Future;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;
import io.vertx.sqlclient.Pool;
import io.vertx.sqlclient.Row;
import io.vertx.sqlclient.templates.SqlTemplate;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

public class RestaurantService {
  private final Pool pool;

  public RestaurantService(Pool pool) {
    this.pool = pool;
  }

  public Future<Void> initDatabase() {
    String createTable = """
      CREATE TABLE IF NOT EXISTS restaurants (
        id INT AUTO_INCREMENT PRIMARY KEY,
        name VARCHAR(255) UNIQUE NOT NULL,
        login VARCHAR(255) NOT NULL,
        password VARCHAR(255) NOT NULL,
        host VARCHAR(255) NOT NULL,
        created TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        updated TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
      )
      """;

    return pool.query(createTable).execute().mapEmpty();
  }

  public Future<Long> countRestaurant() {
    return pool.query("SELECT COUNT(*) AS cnt FROM restaurants")
      .execute()
      .map(rows -> rows.iterator().next().getLong("cnt"));
  }

  public Future<Void> createRestaurant(String name, String login, String password, String host) {

    Map<String, Object> params = new HashMap<>();
    params.put("name", name);
    params.put("login", login);
    params.put("password", password);
    params.put("host", host);

    return SqlTemplate.forUpdate(pool,
        "INSERT INTO restaurants (name, login, password, host) VALUES (#{name}, #{login}, #{password}, #{host})")
      .execute(params)
      .mapEmpty();
  }

  public Future<JsonObject> findByName(String name) {
    return SqlTemplate.forQuery(pool,
        "SELECT id, name, login, password, created, updated, host FROM restaurants WHERE name = #{name}")
      .mapTo(row -> new JsonObject()
        .put("id", row.getInteger("id"))
        .put("name", row.getString("name"))
        .put("login", row.getString("login"))
        .put("password", row.getString("password"))
        .put("created", row.getLocalDateTime("created") != null ?
          row.getLocalDateTime("created").toString() : null)
        .put("updated", row.getLocalDateTime("updated") != null ?
          row.getLocalDateTime("updated").toString() : null)
        .put("host", row.getString("host")))
      .execute(Collections.singletonMap("name", name))
      .map(rows -> rows.iterator().hasNext() ? rows.iterator().next() : null);
  }

  public Future<JsonArray> getAllRestaurants() {
    return pool.query("SELECT id, name, login, created, updated, host FROM restaurants ORDER BY id")
      .execute()
      .map(rows -> {
        JsonArray array = new JsonArray();
        for (Row row : rows) {
          array.add(new JsonObject()
            .put("id", row.getInteger("id"))
            .put("login", row.getString("login"))
            .put("name", row.getString("name"))
            .put("created", row.getLocalDateTime("created") != null ?
              row.getLocalDateTime("created").toString() : null)
            .put("updated", row.getLocalDateTime("updated") != null ?
              row.getLocalDateTime("updated").toString() : null)
            .put("host", row.getString("host")));
        }
        return array;
      });
  }

  public Future<JsonObject> findById(int id) {
    return SqlTemplate.forQuery(pool,
        "SELECT id, name, login, password, host, created, updated FROM restaurants WHERE id = #{id}")
      .mapTo(row -> new JsonObject()
        .put("id", row.getInteger("id"))
        .put("name", row.getString("name"))
        .put("login", row.getString("login"))
        .put("password", row.getString("password"))
        .put("host", row.getString("host"))
        .put("created", row.getLocalDateTime("created") != null ? row.getLocalDateTime("created").toString() : null)
        .put("updated", row.getLocalDateTime("updated") != null ? row.getLocalDateTime("updated").toString() : null))
      .execute(Collections.singletonMap("id", id))
      .map(rows -> rows.iterator().hasNext() ? rows.iterator().next() : null);
  }

  public Future<Void> updateRestaurant(int id, String name, String login, String password, String host) {
    Map<String, Object> params = new HashMap<>();
    params.put("id", id);
    params.put("name", name);
    params.put("login", login);
    params.put("host", host);

    String sql;
    if (password != null && !password.isEmpty()) {
      params.put("password", password);
      sql = "UPDATE restaurants SET name = #{name}, login = #{login}, password = #{password}, host = #{host} WHERE id = #{id}";
    } else {
      sql = "UPDATE restaurants SET name = #{name}, login = #{login}, host = #{host} WHERE id = #{id}";
    }

    return SqlTemplate.forUpdate(pool, sql)
      .execute(params)
      .mapEmpty();
  }

  public Future<Void> deleteRestaurant(int id) {
    return SqlTemplate.forUpdate(pool, "DELETE FROM restaurants WHERE id = #{id}")
      .execute(Collections.singletonMap("id", id))
      .mapEmpty();
  }
}
