#!/bin/sh
set -eu

POOL_ID="${COGNITO_USER_POOL_ID:-us-east-1_BaseAdminWeb}"
POOL_NAME="${COGNITO_USER_POOL_NAME:-base-admin-web}"
REGION="${AWS_DEFAULT_REGION:-us-east-1}"
DATA_DIR="${FLOCI_STORAGE_PERSISTENT_PATH:-/app/data}"
ENV_OUTPUT_DIR="${COGNITO_ENV_OUTPUT_DIR:-/generated}"
ENV_FILE="${ENV_OUTPUT_DIR}/cognito.local.env"

ADMIN_USERNAME="${COGNITO_ADMIN_USERNAME:-admin}"
ADMIN_PASSWORD="${COGNITO_ADMIN_PASSWORD:-Admin123*}"
ADMIN_NAME="${COGNITO_ADMIN_DISPLAY_NAME:-Administrador Base}"

SCANNER_USERNAME="${COGNITO_SCANNER_USERNAME:-scanner}"
SCANNER_PASSWORD="${COGNITO_SCANNER_PASSWORD:-Scanner123*}"
SCANNER_NAME="${COGNITO_SCANNER_DISPLAY_NAME:-Escaneador}"

ADMIN_CLIENT_NAME="${COGNITO_ADMIN_CLIENT_NAME:-base-admin-web-admin}"
SCANNER_CLIENT_NAME="${COGNITO_SCANNER_CLIENT_NAME:-base-admin-web-scanner}"
ADMIN_GROUP="${COGNITO_ADMIN_GROUP:-admins}"
SCANNER_GROUP="${COGNITO_SCANNER_GROUP:-scanners}"

mkdir -p "$DATA_DIR" "$ENV_OUTPUT_DIR"

log() {
  printf '[cognito-bootstrap] %s\n' "$1" >&2
}

pool_exists() {
  aws cognito-idp describe-user-pool --user-pool-id "$POOL_ID" >/dev/null 2>&1
}

create_pool() {
  log "Creando user pool $POOL_ID"
  aws cognito-idp create-user-pool \
    --pool-name "$POOL_NAME" \
    --user-pool-tags "floci:override-id=${POOL_ID}" \
    --policies "PasswordPolicy={MinimumLength=8,RequireUppercase=true,RequireLowercase=true,RequireNumbers=true,RequireSymbols=true}" \
    --username-configuration "CaseSensitive=false" \
    --mfa-configuration OFF \
    --account-recovery-setting "RecoveryMechanisms=[{Priority=1,Name=verified_email}]"
}

find_client_id() {
  client_name="$1"
  aws cognito-idp list-user-pool-clients \
    --user-pool-id "$POOL_ID" \
    --max-results 60 \
    --query "UserPoolClients[?ClientName=='${client_name}'].ClientId | [0]" \
    --output text
}

create_client() {
  client_name="$1"
  existing_id="$(find_client_id "$client_name" || true)"
  if [ -n "$existing_id" ] && [ "$existing_id" != "None" ]; then
    log "App client $client_name ya existe ($existing_id)"
    printf '%s' "$existing_id"
    return 0
  fi

  log "Creando app client $client_name"
  aws cognito-idp create-user-pool-client \
    --user-pool-id "$POOL_ID" \
    --client-name "$client_name" \
    --explicit-auth-flows \
      ALLOW_USER_PASSWORD_AUTH \
      ALLOW_REFRESH_TOKEN_AUTH \
      ALLOW_USER_SRP_AUTH \
    --prevent-user-existence-errors ENABLED \
    --supported-identity-providers COGNITO \
    --query "UserPoolClient.ClientId" \
    --output text
}

create_group_if_needed() {
  group_name="$1"
  description="$2"
  if aws cognito-idp get-group --user-pool-id "$POOL_ID" --group-name "$group_name" >/dev/null 2>&1; then
    log "Grupo $group_name ya existe"
    return 0
  fi

  log "Creando grupo $group_name"
  aws cognito-idp create-group \
    --user-pool-id "$POOL_ID" \
    --group-name "$group_name" \
    --description "$description"
}

user_exists() {
  username="$1"
  aws cognito-idp admin-get-user \
    --user-pool-id "$POOL_ID" \
    --username "$username" >/dev/null 2>&1
}

create_user_if_needed() {
  username="$1"
  password="$2"
  display_name="$3"
  group_name="$4"

  if ! user_exists "$username"; then
    log "Creando usuario $username"
    aws cognito-idp admin-create-user \
      --user-pool-id "$POOL_ID" \
      --username "$username" \
      --message-action SUPPRESS \
      --user-attributes "Name=name,Value=${display_name}"
  else
    log "Usuario $username ya existe"
  fi

  aws cognito-idp admin-set-user-password \
    --user-pool-id "$POOL_ID" \
    --username "$username" \
    --password "$password" \
    --permanent

  aws cognito-idp admin-add-user-to-group \
    --user-pool-id "$POOL_ID" \
    --username "$username" \
    --group-name "$group_name" >/dev/null 2>&1 || true
}

write_env_file() {
  admin_client_id="$1"
  scanner_client_id="$2"

  cat > "$ENV_FILE" <<EOF
# Generado por docker/floci/init/ready.d/10-cognito-bootstrap.sh
COGNITO_USER_POOL_ID=${POOL_ID}
COGNITO_REGION=${REGION}
COGNITO_ISSUER_URI=http://localhost:4566/${POOL_ID}
COGNITO_JWK_SET_URI=http://localhost:4566/${POOL_ID}/.well-known/jwks.json
COGNITO_ADMIN_CLIENT_ID=${admin_client_id}
COGNITO_SCANNER_CLIENT_ID=${scanner_client_id}
COGNITO_ADMIN_GROUP=${ADMIN_GROUP}
COGNITO_SCANNER_GROUP=${SCANNER_GROUP}
AWS_ENDPOINT_URL=http://localhost:4566
AWS_DEFAULT_REGION=${REGION}
AWS_ACCESS_KEY_ID=test
AWS_SECRET_ACCESS_KEY=test
EOF

  log "Variables locales guardadas en $ENV_FILE"
}

log "Iniciando bootstrap de Cognito"

if ! pool_exists; then
  create_pool
else
  log "User pool $POOL_ID ya existe"
fi

ADMIN_CLIENT_ID="$(create_client "$ADMIN_CLIENT_NAME")"
SCANNER_CLIENT_ID="$(create_client "$SCANNER_CLIENT_NAME")"

create_group_if_needed "$ADMIN_GROUP" "Administradores del panel web"
create_group_if_needed "$SCANNER_GROUP" "Usuarios escaner movil/API"

create_user_if_needed "$ADMIN_USERNAME" "$ADMIN_PASSWORD" "$ADMIN_NAME" "$ADMIN_GROUP"
create_user_if_needed "$SCANNER_USERNAME" "$SCANNER_PASSWORD" "$SCANNER_NAME" "$SCANNER_GROUP"

write_env_file "$ADMIN_CLIENT_ID" "$SCANNER_CLIENT_ID"

log "Bootstrap completado"
log "Admin: $ADMIN_USERNAME / $ADMIN_PASSWORD (grupo $ADMIN_GROUP)"
log "Scanner: $SCANNER_USERNAME / $SCANNER_PASSWORD (grupo $SCANNER_GROUP)"