# AI Agent Task: Implement Admin Impersonation Feature

## Branch & Repository Context

**Repository:** `aimclear/amsoil-dlp`
**Working Branch:** `feature/admin-impersonation`
**Base Branch:** `main`

Clone and checkout:

```bash
git clone https://github.com/aimclear/amsoil-dlp.git
cd amsoil-dlp
git checkout feature/admin-impersonation
npm install
```

## Your Mission

Implement the admin impersonation feature following the detailed implementation plan at:

```
docs/plans/2025-12-03-admin-impersonation-implementation.md
```

Read this document thoroughly before starting. It contains:

- Exact file paths for every change
- Complete code snippets ready to implement
- Test cases to write first
- Commit messages to use

## Design Document Reference

The approved design specification is at:

```
docs/plans/2025-12-03-admin-impersonation-design.md
```

Consult this if you need architectural context or rationale for decisions.

## Development Methodology: RED-GREEN-REFACTOR (TDD)

You MUST follow strict TDD for all tasks that include tests:

### RED Phase

1. Write the failing test first
2. Run the test to confirm it fails
3. Verify it fails for the RIGHT reason (not syntax errors, import errors, etc.)

### GREEN Phase

1. Write the MINIMAL code to make the test pass
2. Do not add extra features, optimizations, or "nice to haves"
3. Run the test to confirm it passes

### REFACTOR Phase

1. Clean up the code while keeping tests green
2. Remove duplication
3. Improve naming
4. Run tests again to confirm nothing broke

### TDD Rules

- Never write production code without a failing test
- Never write more test code than necessary to fail
- Never write more production code than necessary to pass
- Commit after each RED-GREEN-REFACTOR cycle

## Task Execution Order

Execute tasks in order (1-12). Each task builds on the previous:

1. **Task 1:** Database Schema - Add isAdmin and AdminAuditLog
2. **Task 2:** Extend NextAuth Types
3. **Task 3:** Update Auth Callbacks for Admin Status
4. **Task 4:** Create Admin Utility Library (TDD)
5. **Task 5:** Update Middleware for Admin Routes
6. **Task 6:** Create Impersonate API Route (TDD)
7. **Task 7:** Create End Session API Route
8. **Task 8:** Create Admin Dealers API Route
9. **Task 9:** Create Admin Stats API Route
10. **Task 10:** Create Admin Dashboard Page
11. **Task 11:** Modify Dashboard Header for Impersonation Mode
12. **Task 12:** Run Full Test Suite and Build

## Commit Strategy

- Commit after completing each task
- Use the exact commit messages provided in the implementation plan
- Do NOT squash commits - we want granular history
- Push to remote after every 2-3 tasks

## Quality Assurance Regimen

### Gate 1: After Each Task

Before moving to the next task, verify:

- [ ] TypeScript compiles: `npx tsc --noEmit` exits with 0
- [ ] If task has tests: `npm test -- <test-file>` passes
- [ ] Code committed with specified message

### Gate 2: After Task 6 (Core API Complete)

Run full verification:

```bash
npx tsc --noEmit
npm test
```

- [ ] All tests pass
- [ ] No new TypeScript errors

### Gate 3: After Task 11 (All Code Complete)

```bash
npx tsc --noEmit
npm test
npm run build
```

- [ ] TypeScript: 0 errors
- [ ] Tests: All pass (existing + new)
- [ ] Build: Exits with 0, no errors

### Gate 4: Manual QA Checklist

You MUST verify each scenario works before considering the task complete:

#### Admin Access Control

- [ ] Visit `/admin` as non-authenticated user → redirects to `/auth/signin`
- [ ] Visit `/admin` as authenticated non-admin → redirects to `/dashboard`
- [ ] Visit `/admin` as admin user → shows admin dashboard

#### Admin Dashboard Functionality

- [ ] Stats cards display (total dealers, by status)
- [ ] Dealer search works (type name, see filtered results)
- [ ] Dealer table paginates correctly
- [ ] "View My Dealer Account" button appears (if admin has dealer)

#### Impersonation Flow

- [ ] Click "Impersonate" on a dealer row
- [ ] Redirected to `/dashboard`
- [ ] Header background changes to amber/orange
- [ ] "ADMIN VIEW" badge visible in header
- [ ] "Return to Admin" button visible
- [ ] All dealer dashboard functionality works normally

#### Return to Admin Flow

- [ ] Click "Return to Admin" button
- [ ] Redirected back to `/admin`
- [ ] Admin session fully restored
- [ ] Can impersonate a different dealer

#### Security Checks

- [ ] Cannot access `/api/admin/*` endpoints without admin session
- [ ] Cannot impersonate while already impersonating (returns 403)
- [ ] Cannot impersonate another admin user (returns 403)
- [ ] Audit logs created for impersonation_start and impersonation_end

#### Database Verification

After running the impersonation flow, verify in database:

```sql
SELECT * FROM "AdminAuditLog" ORDER BY "createdAt" DESC LIMIT 5;
```

- [ ] Records exist with correct adminUserId, dealerUserId, action

## Success Criteria (MUST ALL BE TRUE)

Your task is NOT complete until ALL of these conditions are met:

### Automated Checks

1. `npx tsc --noEmit` → Exit code 0
2. `npm test` → All tests pass (0 failures)
3. `npm run build` → Exit code 0

### Test Coverage

4. `lib/__tests__/admin.test.ts` exists and passes
5. `app/api/admin/impersonate/__tests__/route.test.ts` exists and passes
6. All existing tests still pass

### Manual Verification

7. Admin can log in and see dashboard at `/admin`
8. Admin can search and find dealers
9. Admin can impersonate a dealer
10. Impersonation header shows correctly
11. Admin can return from impersonation
12. Audit logs are created

### Code Quality

13. No `any` types added (except where explicitly shown in plan)
14. No `eslint-disable` comments added
15. No `@ts-ignore` comments added
16. All commits follow the specified messages

## Environment Setup

The project requires:

- Node.js 18+
- PostgreSQL database
- Environment variables (copy from `.env.example` if needed)

Database setup:

```bash
npx prisma migrate dev
```

## Troubleshooting

### Common Issues

**Prisma client not generated:**

```bash
npx prisma generate
```

**Database connection issues:**

- Verify `DATABASE_URL` in `.env.local`
- Ensure PostgreSQL is running

**NextAuth session issues:**

- Verify `NEXTAUTH_SECRET` is set
- Clear cookies and try again

**Type errors after schema change:**

```bash
npx prisma generate
npx tsc --noEmit
```

## Final Deliverable

When complete, push all changes and report:

1. Total commits made
2. Test results summary
3. Build status
4. Manual QA checklist completion status
5. Any deviations from the plan (with justification)

---

**Remember:** Quality over speed. Follow TDD strictly. Do not skip gates.
