package com.cloudhandson.vpdbackoffice.config;

import java.time.Duration;
import org.springframework.boot.context.properties.ConfigurationProperties;

@ConfigurationProperties(prefix = "backoffice")
public record BackofficeProperties(
    Security security,
    Token token,
    Ords ords,
    Ai ai,
    SelectAi selectAi
) {

  public record Security(
      String adminUser,
      String adminPassword,
      String adminPasswordHash,
      boolean guestEnabled,
      String guestUser,
      String guestPassword,
      String guestPasswordHash,
      boolean requireHttps,
      boolean rememberMeEnabled,
      String rememberMeKey,
      int rememberMeDays
  ) {

    /** Remember-me is intentionally unavailable over HTTP or without a stable secret key. */
    public boolean rememberMeConfigured() {
      return requireHttps
          && rememberMeEnabled
          && rememberMeKey != null
          && !rememberMeKey.isBlank()
          && rememberMeDays >= 1
          && rememberMeDays <= 90;
    }

    public int rememberMeValiditySeconds() {
      return rememberMeDays * 24 * 60 * 60;
    }

    public boolean guestConfigured() {
      return guestEnabled
          && guestUser != null
          && !guestUser.isBlank()
          && ((guestPassword != null && !guestPassword.isBlank())
              || (guestPasswordHash != null && !guestPasswordHash.isBlank()));
    }
  }

  public record Token(int maxDays) {
  }

  public record Ords(String baseUrl, Duration timeout, Duration agentTimeout) {
  }

  public record Ai(
      boolean enabled,
      String provider,
      String baseUrl,
      String model,
      String apiKey,
      Duration timeout,
      String embeddingModel,
      String ociConfigFile,
      String ociProfile,
      String ociRegion,
      String ociCompartmentId
  ) {

    public Ai(boolean enabled, String baseUrl, String model, String apiKey, Duration timeout) {
      this(enabled, "openai", baseUrl, model, apiKey, timeout, "", "", "", "", "");
    }
  }

  /** Separate ADB connection because Select AI profiles are owned by a schema-specific account. */
  public record SelectAi(
      String dbUrl,
      String dbUsername,
      String dbPassword,
      String profile,
      Boolean fewShotEnabled,
      Integer fewShotTopK
  ) {

    public boolean configured() {
      return dbUrl != null && !dbUrl.isBlank()
          && dbUsername != null && !dbUsername.isBlank()
          && dbPassword != null && !dbPassword.isBlank()
          && profile != null && !profile.isBlank();
    }
  }
}
