package su.xserver.iikocon;

import io.vertx.core.json.JsonObject;
import io.vertx.ext.web.RoutingContext;
import io.vertx.ext.web.Session;

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();
        System.out.println("User found: " + user.encode());

        boolean passwordOk = userService.checkPassword(password, user.getString("password"));
        System.out.println("Password OK: " + passwordOk);

        if (passwordOk) {
          // Надёжное получение флага активности
          Boolean active = user.getBoolean("active");
          if (active == null) {
            // Если поле отсутствует, пробуем получить как Integer (на случай TINYINT)
            Integer activeInt = user.getInteger("active");
            active = activeInt != null && activeInt == 1;
          }
          System.out.println("Active flag: " + active);

          if (!active) {
            System.out.println("Sending: Account not activated");
            ctx.response().setStatusCode(401).end("Account not activated");
            return;
          }

          Session session = ctx.session();
          session.put("userId", user.getInteger("id"));
          session.put("login", user.getString("login"));
          ctx.response().end(new JsonObject().put("success", true).put("login", user.getString("login")).encode());
        } else {
          System.out.println("Sending: Invalid credentials (password mismatch)");
          ctx.response().setStatusCode(401).end("Invalid credentials");
        }
      } else {
        System.out.println("Sending: Invalid credentials (user not found or error)");
        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();
    }
  }
}
