#!/bin/bash

# Setup script for Azure Authentication with FastMSSQL
# This script helps configure Azure AD authentication after Terraform deployment

set -e

echo "🚀 FastMSSQL Azure Authentication Setup"
echo "========================================="

# Check if we're in the terraform directory
if [ ! -f "terraform.tfstate" ]; then
    echo "❌ Error: terraform.tfstate not found. Please run this script from the terraform directory."
    echo "   cd terraform && ../scripts/setup_azure_auth.sh"
    exit 1
fi

echo "📋 Getting Terraform outputs..."

# Get outputs from Terraform
SQL_SERVER=$(terraform output -raw azure_sql_server_for_env)
DATABASE=$(terraform output -raw azure_sql_database_for_env)
CLIENT_ID=$(terraform output -raw service_principal_client_id)
CLIENT_SECRET=$(terraform output -raw service_principal_client_secret)
TENANT_ID=$(terraform output -raw tenant_id)
ADMIN_USER=$(terraform output -raw sql_server_name)

echo "✅ Retrieved configuration from Terraform"
echo "   Server: $SQL_SERVER"
echo "   Database: $DATABASE"
echo "   Service Principal: $CLIENT_ID"

# Create environment file
ENV_FILE="../../setup_files/azure.env"
echo "📝 Creating $ENV_FILE..."

cat > "$ENV_FILE" << EOF
# Azure Authentication Configuration
# Generated by setup_azure_auth.sh on $(date)

# Azure SQL Server Configuration
AZURE_SQL_SERVER=$SQL_SERVER
AZURE_SQL_DATABASE=$DATABASE

# Service Principal Authentication
AZURE_CLIENT_ID=$CLIENT_ID
AZURE_CLIENT_SECRET=$CLIENT_SECRET
AZURE_TENANT_ID=$TENANT_ID

# Note: For production, store CLIENT_SECRET in Azure Key Vault or similar secure storage
EOF

echo "✅ Created $ENV_FILE"

# Create SQL script for database permissions
SQL_SCRIPT="../../setup_files/database/setup_database_permissions.sql"
echo "📝 Creating $SQL_SCRIPT..."

# Get the application display name from Terraform
APP_NAME=$(terraform output -raw sql_server_name)-app

cat > "$SQL_SCRIPT" << EOF
-- Database permissions setup for Azure AD Service Principal
-- Connect to your database as an Azure AD administrator and run these commands

-- Create user for the Service Principal
CREATE USER [$APP_NAME] FROM EXTERNAL PROVIDER;

-- Grant basic permissions (adjust as needed for your application)
ALTER ROLE db_datareader ADD MEMBER [$APP_NAME];
ALTER ROLE db_datawriter ADD MEMBER [$APP_NAME];
ALTER ROLE db_ddladmin ADD MEMBER [$APP_NAME];  -- Optional: for DDL operations

-- Verify the user was created
SELECT name, type_desc, authentication_type_desc 
FROM sys.database_principals 
WHERE name = '$APP_NAME';

-- Grant additional permissions if needed:
-- GRANT SELECT, INSERT, UPDATE, DELETE ON SCHEMA::dbo TO [$APP_NAME];
-- GRANT EXECUTE ON SCHEMA::dbo TO [$APP_NAME];  -- For stored procedures
EOF

echo "✅ Created $SQL_SCRIPT"

echo ""
echo "🎯 Next Steps:"
echo "=============="
echo ""
echo "1. Load environment variables:"
echo "   source $ENV_FILE"
echo ""
echo "2. Set up database permissions:"
echo "   - Connect to your database using Azure Data Studio or SSMS"
echo "   - Log in as your Azure AD administrator"
echo "   - Run the SQL commands in: $SQL_SCRIPT"
echo ""
echo "3. Test the connection:"
echo "   cd ../.. && env \$(cat setup_files/azure.env | grep -v '^#' | xargs) uv run python setup_files/test_azure_simple.py"
echo ""
echo "🔐 Alternative: Use Azure CLI for quick testing:"
echo "   az login"
echo "   export AZURE_SQL_SERVER=\"$SQL_SERVER\""
echo "   export AZURE_SQL_DATABASE=\"$DATABASE\""
echo "   # Then use AzureCredential.default() in your code"
echo ""

# Show the instructions output from Terraform
echo "📋 Terraform Instructions:"
terraform output azure_auth_instructions

echo ""
echo "✨ Setup complete! Your Azure authentication is ready to use."