#!/bin/bash
set -e

echo "Setting up Management Console UserPool..."


# UserPool作成
echo "🚀 Creating Management EndUser UserPool..."
USER_POOL_ID=$(aws cognito-idp create-user-pool \
  --pool-name "local-management-user-pool" \
  --schema \
    Name=tenant_id,AttributeDataType=String,Mutable=true,StringAttributeConstraints="{MinLength=36,MaxLength=256}" \
    Name=user_id,AttributeDataType=String,Mutable=true,StringAttributeConstraints="{MinLength=36,MaxLength=256}" \
  --username-attributes "" \
  --alias-attributes "preferred_username" \
  --admin-create-user-config "AllowAdminCreateUserOnly=true" \
  --endpoint-url $AWS_ENDPOINT_URL \
  --query 'UserPool.Id' --output text)

echo "UserPool created: $USER_POOL_ID"



# アプリケーションクライアント作成（テナント: alpha）
# ローカルトークン取得用のユーザー作成のため、ALLOW_ADMIN_USER_PASSWORD_AUTHを有効化する
echo "🚀 Creating UserPool Client for alpha tenant..."
aws cognito-idp create-user-pool-client \
  --user-pool-id "$USER_POOL_ID" \
  --client-name "user_application_client#alpha" \
  --no-generate-secret \
  --refresh-token-validity 30 \
  --access-token-validity 60 \
  --id-token-validity 60 \
  --token-validity-units "RefreshToken=days,AccessToken=minutes,IdToken=minutes" \
  --explicit-auth-flows "ALLOW_USER_SRP_AUTH" "ALLOW_REFRESH_TOKEN_AUTH" "ALLOW_ADMIN_USER_PASSWORD_AUTH" \
  --read-attributes "custom:tenant_id" "custom:user_id" \
  --write-attributes "email" "preferred_username" \
  --supported-identity-providers "COGNITO" \
  --prevent-user-existence-errors "ENABLED" \
  --endpoint-url $AWS_ENDPOINT_URL > /dev/null

echo "UserPool Client created: user_application_client#alpha"


# テストユーザー作成（CSVから読み込み）
echo "🚀 Creating test users from CSV..."

USER_FIXTURE_FILE="$FIXTURE_DIR/100.users.csv"

tail -n +2 "$USER_FIXTURE_FILE" | while IFS=',' read -r user_id tenant_id display_id display_name email updated_at; do
  USERNAME="USR_${tenant_id}_${user_id}"
  PREFERRED_USERNAME="${tenant_id}_${display_id}"

  # 属性を組み立て
  USER_ATTRS=(
    "Name=preferred_username,Value=${PREFERRED_USERNAME}"
    "Name=custom:tenant_id,Value=${tenant_id}"
    "Name=custom:user_id,Value=${user_id}"
  )

  # emailが存在する場合のみ追加
  if [ -n "$email" ]; then
    USER_ATTRS+=(
      "Name=email,Value=${email}"
      "Name=email_verified,Value=true"
    )
  fi

  aws cognito-idp admin-create-user \
    --user-pool-id "$USER_POOL_ID" \
    --username "$USERNAME" \
    --user-attributes "${USER_ATTRS[@]}" \
    --endpoint-url $AWS_ENDPOINT_URL > /dev/null

  echo "Created user: $USERNAME ($display_name)"
done

# トークン取得用のユーザー作成(alphaテナント: admin)
aws cognito-idp admin-create-user \
  --user-pool-id "$USER_POOL_ID" \
  --username "$LOCAL_COGNITO_ADMIN_USERNAME" \
  --user-attributes \
    Name=custom:tenant_id,Value=00000001-0000-0000-0000-000000000000 \
    Name=custom:user_id,Value=00000001-0000-0000-0000-000000000000 \
  --endpoint-url $AWS_ENDPOINT_URL > /dev/null
aws cognito-idp admin-set-user-password \
  --user-pool-id "$USER_POOL_ID" \
  --username "$LOCAL_COGNITO_ADMIN_USERNAME" \
  --password "$LOCAL_COGNITO_ADMIN_PASSWORD" \
  --permanent \
  --endpoint-url $AWS_ENDPOINT_URL > /dev/null



# PoolIDを.envに書き出し
echo "MANAGEMENT_USER_POOL_ID=$USER_POOL_ID" >> $ENV_FILE
echo "UserPool IDs written to $ENV_FILE"

echo "✅ Management Console UserPool setup completed! (Pool ID: $USER_POOL_ID)"
