# Google Cloud PostgreSQL Setup (Step by Step)

This guide creates the tables used by the `realworld_support_multi_agent` example.

## 1. Create a Cloud SQL PostgreSQL instance
1. Open Google Cloud Console.
2. Go to `SQL`.
3. Click `Create instance`.
4. Choose `PostgreSQL`.
5. Set:
   - Instance ID: e.g. `support-pg-prod`
   - Password: set a strong admin password
   - Region: same region as your runtime
6. Click `Create`.

## 2. Create database and user
1. Open the created instance.
2. Go to `Databases` -> `Create database`.
3. Name: `support_ops`.
4. Go to `Users` -> `Add user account`.
5. Create app user, e.g.:
   - Username: `support_app`
   - Password: strong app password

## 3. Allow connectivity
Choose one approach:

- Private IP (recommended for production):
  - Enable Private IP.
  - Connect runtime from same VPC/network.

- Public IP (dev/test):
  - Enable Public IP.
  - Add your client/runtime IP under `Authorized networks`.

## 4. Connect with `psql`
Use Cloud Shell or your machine:

```bash
psql "host=<INSTANCE_IP_OR_HOST> port=5432 dbname=support_ops user=support_app sslmode=require"
```

## 5. Create tables
Run the SQL in:

- `schema_support_ops.sql`

From `psql`:

```sql
\i schema_support_ops.sql
```

Or copy/paste the file contents directly.

## 6. Seed minimum test data
Insert a sample account and records:

```sql
INSERT INTO customer_accounts (account_id, plan_name, mrr, status, renewal_date)
VALUES ('acct_001', 'Growth', 299.00, 'active', CURRENT_DATE + INTERVAL '45 days')
ON CONFLICT (account_id) DO NOTHING;

INSERT INTO invoices (invoice_id, account_id, due_date, amount, status)
VALUES ('INV-2091', 'acct_001', CURRENT_DATE - INTERVAL '3 days', 299.00, 'overdue')
ON CONFLICT (invoice_id) DO NOTHING;

INSERT INTO payment_disputes (account_id, created_at, amount, reason, status)
VALUES ('acct_001', NOW() - INTERVAL '1 day', 299.00, 'duplicate_charge', 'open');
```

## 7. Validate queries used by the workflow
```sql
SELECT * FROM customer_accounts WHERE account_id = 'acct_001';
SELECT * FROM invoices WHERE account_id = 'acct_001' ORDER BY due_date DESC LIMIT 5;
SELECT * FROM payment_disputes WHERE account_id = 'acct_001' ORDER BY created_at DESC LIMIT 10;
```

## 8. Validate write path (`support_case_actions`)
```sql
INSERT INTO support_case_actions (
  case_id, account_id, user_id, action, risk_level, reasoning
) VALUES (
  'case_test_001', 'acct_001', 'user_001', 'offer_payment_plan', 'medium', 'Test write'
)
RETURNING id, created_at;
```

## 9. Connect this DB as an AIEL Postgres resource
1. In your AIEL integration UI/backend, create a Postgres connection/resource for this DB.
2. Copy the generated UUID resource ID.
3. Pass it in event payload as:
   - `postgres_resource_id`

## 10. Operational recommendations
- Grant app user only required permissions.
- Enable automated backups and PITR.
- Use SSL/TLS and rotate credentials regularly.
- Add indexes if volume grows (example: `invoices(account_id, due_date desc)`).

