# Implementation Plan: Checkout System Audit & Logic Hardening

## Phase 1: Research & Current State Audit (Scouting)
Goal: Identify current implementation gaps and technical debt in the checkout flow.

- [x] Task 1: Comprehensive Codebase Scan [Skills: codebase_investigator, context7-mcp, find-docs] [MCP: Search, FileSystem, context7]
    - [x] [Scout] Map the full flow from `actions/checkout.ts` to `lib/internal/fulfillment.ts` and the final Database Order creation.
    - [x] [Scout] Identify where raw SQL might be bypassing the Repository Pattern.
    - [x] [Scout] Audit all `console.log` and `logger` calls in the checkout flow for PII exposure.
- [x] Task 2: Analyze Existing Test Coverage [Skills: testing-code, context7-mcp, find-docs] [MCP: Search, context7]
    - [x] [Scout] Review `hooks/useCheckoutStore.test.ts` and other relevant tests. Identify missing integration tests for Stripe webhooks and partial failure scenarios.
- [~] Meta: Phase 1 Completion Verification
    - [ ] [Manual] User review of the identified logic gaps and PII findings.

## Phase 2: Data Validation & Typing Hardening
Goal: Enforce strict Zod validation and comprehensive TypeScript interfaces across all data boundaries.

- [x] Task 3: Implement Strict Zod Schemas [Skills: managing-schemas, software-architecture, context7-mcp, find-docs] [MCP: FileSystem, context7]
    - [x] [Scout] Check existing schemas in `lib/db/repositories/` and `actions/`.
    - [x] Write Failing Tests: Create integration tests in `lib/internal/fulfillment.test.ts` to verify that invalid webhook payloads are strictly rejected.
    - [x] Implement: Define and enforce `CartInput`, `StripeSessionConfig`, and `FulfillmentData` schemas with `z.coerce.number()` for all numeric fields.
- [x] Task 4: Hardening External Sync Types [Skills: fullstack-development, context7-mcp, find-docs] [MCP: FileSystem, context7]
    - [x] [Scout] Review Stripe metadata structure currently used in `lib/internal/fulfillment.ts`.
    - [x] Write Failing Tests: Verify that missing metadata or mismatched types trigger a `BadRequestError`.
    - [x] Implement: Ensure all metadata extracted from Stripe sessions is strictly typed and validated before use.
- [x] Meta: Phase 2 Completion Verification
    - [x] [Manual] Verify all Zod schemas are used at the Repository and Action boundaries. [checkpoint: 288e534]

## Phase 3: Logic Hardening (Idempotency & Atomicity)
Goal: Ensure the checkout flow is resilient to race conditions and partial system failures.

- [x] Task 5: Implement Stripe & Database Idempotency [Skills: securing-applications, software-architecture, context7-mcp, find-docs] [MCP: FileSystem, context7]
    - [x] [Scout] Search for existing `idempotency_key` usage in the codebase.
    - [x] Write Failing Tests: Create a stress test that simulates 10 concurrent requests to the checkout action for the same user/cart.
    - [x] Implement: Add `idempotency_key` logic using unique cart/user hashes to prevent duplicate Stripe sessions and orders.
- [x] Task 6: Ensure Multi-System Logical Atomicity [Skills: architecting-automation, software-architecture, context7-mcp, find-docs] [MCP: FileSystem, context7]
    - [x] [Scout] Examine the PostgreSQL transaction blocks in `lib/internal/fulfillment.ts`.
    - [x] Write Failing Tests: Create a test that simulates a Redis failure *after* successful payment and verify that the database order creation can be safely retried.
    - [x] Implement: Wrap inventory updates (Redis) and order creation (Postgres) in a reliable sync-or-retry mechanism within a transaction.
- [x] Task 7: Stock Consistency Audit [Skills: fullstack-development, context7-mcp, find-docs] [MCP: FileSystem, context7]
    - [x] [Scout] Check inventory locking mechanisms in `InventoryRepository`.
    - [x] Write Failing Tests: Simulate stock-outs occurring between session creation and payment.
    - [x] Implement: Add a final stock check inside the fulfillment webhook before confirming the order.
- [ ] Meta: Phase 3 Completion Verification
    - [ ] [Manual] Verify idempotency and atomicity with simulated failure tests. [checkpoint: <sha>]

## Phase 4: Security, Logging & Final Verification
Goal: Ensure zero PII leakage and verify the system under high-stress scenarios.

- [x] Task 8: PII Audit & Logging Sanity [Skills: securing-applications, context7-mcp, find-docs] [MCP: Search, FileSystem, context7]
    - [x] [Scout] Re-verify all `logger.info` and `logger.error` locations identified in Task 1.
    - [x] Implement: Redact or mask all PII (email, address, name) in checkout logs. Use standardized log wrappers.
- [-] Task 9: Final E2E Stress Test (Skipped per user request)
- [x] Meta: Phase 4 Completion Verification
    - [x] [Manual] Run final build, lint, and test suite. [checkpoint: 58e3f21]

## Quality Gates (Final)
- [ ] 100% Code Coverage on new logic.
- [ ] Zero build errors (`pnpm build`).
- [ ] Zero linting/typing errors.
- [ ] Successful E2E run.
