# Payout Retry Processor Lambda

Retries failed Stripe payouts daily. Triggered by EventBridge Scheduler at 7 AM EST.

## Prerequisites

- Node.js 20.x
- PostgreSQL database with rentals data
- Stripe account with test API key (`sk_test_...`)

## Setup

1. Install shared dependencies:

   ```bash
   cd lambdas/shared
   npm install
   ```

2. Install Lambda dependencies:
   ```bash
   cd lambdas/payoutRetryProcessor
   npm install
   ```

## Environment Variables

| Variable            | Description                                    |
| ------------------- | ---------------------------------------------- |
| `DATABASE_URL`      | PostgreSQL connection string                   |
| `STRIPE_SECRET_KEY` | Stripe API key (use `sk_test_...` for testing) |
| `FRONTEND_URL`      | For email template links                       |
| `SES_FROM_EMAIL`    | Sender email address                           |
| `SES_FROM_NAME`     | Sender display name                            |
| `EMAIL_ENABLED`     | Set to `true` to send emails                   |

## Local Testing

Run the Lambda locally using your dev environment:

```bash
cd lambdas/payoutRetryProcessor
node test-local.js
```

This will:

- Query your local database for failed payouts
- Attempt Stripe transfers (use test mode!)
- Send email notifications if `EMAIL_ENABLED=true`

## Creating Test Data

To test the retry logic, create a rental with failed payout status:

```sql
UPDATE "Rentals"
SET "payoutStatus" = 'failed'
WHERE id = '<rental-id>'
  AND status = 'completed'
  AND "paymentStatus" = 'paid';
```

## Verifying Results

After running the test:

1. Check console output for success/failure counts
2. Query the database:
   ```sql
   SELECT id, "payoutStatus", "stripeTransferId", "payoutProcessedAt"
   FROM "Rentals"
   WHERE id = '<rental-id>';
   ```
3. Check Stripe Dashboard for new transfers
4. Check email inbox if emails are enabled

## AWS Deployment

When deploying to AWS:

1. Create Lambda function with Node.js 20.x runtime
2. Set timeout to 60 seconds (batch processing)
3. Set memory to 256 MB
4. Configure EventBridge Scheduler with cron: `cron(0 12 * * ? *)` (7 AM EST = 12:00 UTC)
5. Add environment variables listed above
6. Configure DLQ for failed invocations

## Architecture

```
EventBridge Scheduler (7 AM EST daily)
         |
         v
    Lambda Function
         |
         +-- Query failed payouts from PostgreSQL
         |
         +-- For each failed payout:
         |     +-- Reset status to "pending"
         |     +-- Create Stripe transfer
         |     +-- Update rental record
         |     +-- Send email notification
         |
         v
    Return summary (success/failure counts)
```
