# Specification: Checkout System Audit & Logic Hardening

## 1. Overview
Audit and refactor the complete end-to-end checkout flow (Cart -> Stripe Session -> Fulfillment -> Database Order) to ensure absolute data integrity, strict type safety, and resilience against race conditions or partial failures.

## 2. Functional Requirements
- **Idempotency & Race Condition Prevention**:
    - Implement `idempotency_key` logic for all Stripe API calls and internal Database order creation.
    - Ensure that multiple identical checkout attempts (e.g., double-clicks or retry loops) result in only one Stripe Session and one Database Order.
- **Logical Atomicity (Multi-System Sync)**:
    - All side effects (Inventory decrement in Redis, Customer updates, Stripe Metadata sync) MUST occur within a PostgreSQL transaction block or be handled by a reliable compensation mechanism.
    - If a post-payment fulfillment step fails (e.g., Redis is down), the system must be able to retry fulfillment without creating duplicate orders.
- **Strict Data Processing & Typing**:
    - Use Zod schemas for EVERY data boundary:
        - `CartInput` -> `StripeSessionConfig`
        - `StripeWebhookPayload` -> `FulfillmentData`
        - `FulfillmentData` -> `DatabaseOrderSchema`
    - Ensure all numeric fields from PostgreSQL are coerced correctly using `z.coerce.number()`.
    - No use of `any` or `unknown` without immediate narrowing.
- **Stock Consistency**:
    - Validate stock availability at the moment of Stripe Session creation AND during the fulfillment webhook.
    - Handle edge cases where stock is depleted between session creation and payment completion.
- **Security & Privacy**:
    - Audit all checkout-related logs to ensure zero PII (Emails, Names, Addresses) is logged.
    - Ensure Stripe `client_secret` and other sensitive tokens are never exposed in server logs.

## 3. Non-Functional Requirements
- **Performance**: Critical checkout API endpoints (Session creation, Webhook handling) must respond in < 200ms.
- **Reliability**: Implement retry logic with exponential backoff for transient failures (e.g., Redis/Postgres connection blips).
- **Strictness**: 100% adherence to the project's Repository Pattern and Zod validation standards.

## 4. Acceptance Criteria
- [ ] 100% test coverage for the checkout flow using the **Anti-Mocking** approach (real Postgres/Redis).
- [ ] Successful E2E Playwright test covering a full purchase flow.
- [ ] Verified Idempotency: Multiple webhook deliveries for the same `checkout.session.completed` event result in exactly one order and one inventory decrement.
- [ ] Verified Atomicity: A simulated crash after Stripe payment but before inventory sync triggers a successful recovery/retry without data corruption.
- [ ] Zero PII found in logs during a simulated checkout run.

## 5. Implementation Constraints (No Ambiguity Clause)
Implementers MUST provide line numbers and code snippets for all proposed changes. No speculative inference allowed. All database access must go through the Repository layer (`lib/db/repositories/`).

## 6. Out of Scope
- Frontend UI/UX redesign (this is a logic and data integrity audit).
- Changes to the physical shipping/fulfillment logic (external to the system).
