# Implementation Plan: DynamoDB Heavy Rotation Test

## Overview
Create a standalone DynamoDB-powered test in the **`dynamo-test`** folder that fetches 50 refresh tokens from DynamoDB and runs heavy rotation analysis. This keeps the working `api-test` folder untouched.

## Files to Create in `dynamo-test/`

### 1. Copy from `api-test/` (preserving working code)
- **`config.ts`** - Spotify API types and interfaces
- **`auth.ts`** - SpotifyAuth class for token management
- **`spotify-client.ts`** - SpotifyClient wrapper with auto-refresh
- **`fetch-heavy-rotation.ts`** - HeavyRotationFetcher class

### 2. Create New Files in `dynamo-test/`

**`package.json`** - New package with dependencies:
```json
{
  "dependencies": {
    "axios": "^1.6.0",
    "dotenv": "^16.3.1",
    "@aws-sdk/client-dynamodb": "^3.370.0",
    "@aws-sdk/client-sts": "^3.370.0",
    "@aws-sdk/util-dynamodb": "^3.370.0",
    "@aws-sdk/credential-providers": "^3.370.0"
  },
  "devDependencies": {
    "tsx": "^4.7.0",
    "typescript": "^5.3.0",
    "@types/node": "^20.10.0"
  }
}
```

**`.env`** - Configuration file:
```
SPOTIFY_CLIENT_ID=...
SPOTIFY_CLIENT_SECRET=...
AWS_PROFILE=songwhip
ALBUMID=6644715
```

**`tsconfig.json`** - TypeScript config (copy from api-test)

**`dynamodb-client.ts`** - DynamoDB query logic:
- Initialize DynamoDBClient with AWS role assumption
- Use local IAM credentials to assume `songwhip-role` in account `926734670777`
- `fetchRefreshTokens(albumId, limit)` function
- Query table: `songwhip-release-tasks-production`
- Partition key: `group:album{ALBUMID}`
- Sort key begins with: `task:spotify-presave`
- Extract `refreshToken` field from results

**`test.ts`** - Main test runner:
- Load config from `.env`
- Fetch 50 refresh tokens via `fetchRefreshTokens()`
- For each token:
  - Initialize SpotifyAuth with refresh token
  - Call `ensureValidToken()`
  - Fetch heavy rotation for 3 time ranges
  - Log results
- Display summary statistics

**`.gitignore`** - Ignore sensitive files:
```
.env
node_modules/
```

## Implementation Details

### AWS Role Assumption (using awsume)
Using AWS SDK v3 with profile-based credentials:
```typescript
import { fromIni } from '@aws-sdk/credential-providers';
import { DynamoDBClient } from '@aws-sdk/client-dynamodb';

// Reads credentials from AWS_PROFILE environment variable
// Requires running: awsume songwhip
const dynamoClient = new DynamoDBClient({
  region: 'us-east-1',
  credentials: fromIni({
    profile: process.env.AWS_PROFILE || 'songwhip',
  }),
});
```

**Note:** You must run `awsume songwhip` before running the test to generate temporary credentials with MFA.

### DynamoDB Query Pattern
Using AWS SDK v3 standard approach:
```typescript
const command = new QueryCommand({
  TableName: 'songwhip-release-tasks-production',
  KeyConditionExpression: 'partitionKey = :pk AND begins_with(sortKey, :sk)',
  ExpressionAttributeValues: {
    ':pk': { S: `group:album${albumId}` },
    ':sk': { S: 'task:spotify-presave' },
  },
  Limit: 50,
});
```

### Test Execution Flow
1. Validate AWS/Spotify credentials from `.env`
2. Query DynamoDB for refresh tokens
3. Process each fan sequentially (to avoid rate limits)
4. Log progress and results for each fan
5. Display aggregate summary

## Setup Steps

### 1. Configure AWS CLI Profile for Songwhip Account
Follow the team's standard AWS access process:

**a) Set profile name:**
```bash
export PROFILE_NAME=songwhip
```

**b) Create the profile (assumes you already have `prod` profile configured):**
```bash
aws configure set source_profile prod --profile $PROFILE_NAME
```

**c) Configure role session name (required for auditing):**
```bash
export AWS_USERNAME=$(aws sts get-caller-identity --query 'Arn' --output text | cut -d '/' -f2)
aws configure set role_session_name $AWS_USERNAME --profile $PROFILE_NAME
```

**d) Configure the role ARN:**
```bash
export ROLE_ARN=arn:aws:iam::926734670777:role/songwhip-role
aws configure set role_arn ${ROLE_ARN} --profile $PROFILE_NAME
```

Your `~/.aws/config` should now have:
```ini
[profile songwhip]
source_profile = prod
role_session_name = <your_aws_username>
role_arn = arn:aws:iam::926734670777:role/songwhip-role
```

### 2. Install Dependencies
```bash
cd dynamo-test/
npm install
```

### 3. Configure Environment Variables
Create `.env` file with AWS profile and Spotify credentials

### 4. Run the Test
```bash
awsume songwhip  # Generate temporary credentials with MFA
npm test         # Run the test
```

## Why This Approach
- **Isolated**: No changes to working `api-test` folder
- **Reusable**: Copies proven auth/client/fetcher logic
- **Self-contained**: Complete standalone test environment
- **Production data**: Tests with real presave users from DynamoDB
