package su.xserver.iikocon.handler;

import io.vertx.core.json.JsonObject;
import io.vertx.ext.web.RoutingContext;
import io.vertx.ext.web.Session;
import su.xserver.iikocon.service.UserService;

public class AuthHandler {
  private final UserService userService;

  public AuthHandler(UserService userService) {
    this.userService = userService;
  }

  public void handleLogin(RoutingContext ctx) {
    JsonObject body = ctx.body().asJsonObject();
    String login = body.getString("login");
    String password = body.getString("password");

    if (login == null || password == null) {
      ctx.response().setStatusCode(400).end("Missing credentials");
      return;
    }

    userService.findByLoginOrEmail(login).onComplete(ar -> {
      if (ar.succeeded() && ar.result() != null) {
        JsonObject user = ar.result();

        boolean passwordOk = userService.checkPassword(password, user.getString("password"));

        if (passwordOk) {
          Boolean active = user.getBoolean("active");
          if (active == null) {
            Integer activeInt = user.getInteger("active");
            active = activeInt != null && activeInt == 1;
          }

          if (!active) {
            ctx.response().setStatusCode(401).end("Account not activated");
            return;
          }

          // Получаем реальный IP клиента (с учётом прокси, если настроен)
          String clientIp = ctx.get("realClientIp");
          if (clientIp == null) {
            clientIp = ctx.request().remoteAddress().host();
          }

          // Обновляем IP в БД (асинхронно, не дожидаемся ответа)
          userService.updateUserIp(user.getInteger("id"), clientIp)
            .onFailure(err -> System.err.println("Failed to update IP for user " + user.getInteger("id") + ": " + err.getMessage()));

          Session session = ctx.session();
          session.put("userId", user.getInteger("id"));
          session.put("login", user.getString("login"));
          session.put("role", user.getString("role"));
          session.put("language", user.getString("language"));
          ctx.response().end(new JsonObject().put("success", true).put("login", user.getString("login")).encode());
        } else {
          ctx.response().setStatusCode(401).end("Invalid credentials");
        }
      } else {
        ctx.response().setStatusCode(401).end("Invalid credentials");
      }
    });
  }

  public void handleLogout(RoutingContext ctx) {
    Session session = ctx.session();
    if (session != null) {
      session.destroy();
    }
    // Явное удаление cookie сессии
    ctx.response().removeCookie("admin.session");
    ctx.response().end(new JsonObject().put("success", true).encode());
  }

  public void requireAuth(RoutingContext ctx) {
    Session session = ctx.session();
    if (session == null || session.get("userId") == null) {
      ctx.response().setStatusCode(401).end("Unauthorized");
    } else {
      ctx.next();
    }
  }
}
