File size: 27,879 Bytes
584ed90
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
PRAGMA foreign_keys = ON;
PRAGMA journal_mode = WAL;
PRAGMA busy_timeout = 5000;

CREATE TABLE IF NOT EXISTS meta (
    key TEXT PRIMARY KEY,
    value TEXT NOT NULL
);

CREATE TABLE IF NOT EXISTS catalog_products (
    asin TEXT PRIMARY KEY,
    slug TEXT NOT NULL,
    title TEXT NOT NULL,
    brand TEXT NOT NULL,
    capacity TEXT NOT NULL,
    color TEXT NOT NULL,
    price_minor INTEGER NOT NULL CHECK (price_minor >= 0),
    list_price_minor INTEGER,
    currency TEXT NOT NULL,
    rating TEXT NOT NULL,
    reviews INTEGER NOT NULL CHECK (reviews >= 0),
    image_path TEXT NOT NULL,
    badge TEXT NOT NULL DEFAULT '',
    evidence_class TEXT NOT NULL
);

-- Transaction-ready offers are intentionally separate from the frozen search
-- catalog.  This lets current direct-PDP evidence override an older search
-- offer without changing the benchmark's nine-result catalog contract.
CREATE TABLE IF NOT EXISTS commerce_offers (
    asin TEXT PRIMARY KEY,
    slug TEXT NOT NULL,
    canonical_path TEXT NOT NULL,
    title TEXT NOT NULL,
    brand TEXT NOT NULL,
    capacity TEXT NOT NULL,
    color TEXT NOT NULL,
    price_minor INTEGER NOT NULL CHECK (price_minor >= 0),
    list_price_minor INTEGER CHECK (list_price_minor IS NULL OR list_price_minor >= 0),
    currency TEXT NOT NULL,
    rating TEXT NOT NULL,
    reviews INTEGER NOT NULL CHECK (reviews >= 0),
    image_path TEXT NOT NULL,
    badge TEXT NOT NULL DEFAULT '',
    evidence_class TEXT NOT NULL,
    source TEXT NOT NULL CHECK (source IN ('task-fixture', 'direct-pdp'))
);

-- Presentation is intentionally separate from the transaction quote registry.
-- Every known ASIN gets one complete display payload, while provenance remains
-- internal and commerce_offers stays authoritative for price and identity.
CREATE TABLE IF NOT EXISTS product_display_catalog (
    asin TEXT PRIMARY KEY REFERENCES commerce_offers(asin) ON DELETE CASCADE,
    source_index INTEGER NOT NULL UNIQUE CHECK (source_index >= 0),
    provenance TEXT NOT NULL CHECK (provenance IN ('direct','legacy','simulated')),
    payload_json TEXT NOT NULL
);

CREATE TABLE IF NOT EXISTS product_details (
    asin TEXT PRIMARY KEY REFERENCES catalog_products(asin) ON DELETE CASCADE,
    payload_json TEXT NOT NULL
);

CREATE TABLE IF NOT EXISTS accounts (
    account_id INTEGER PRIMARY KEY AUTOINCREMENT,
    email_normalized TEXT NOT NULL UNIQUE,
    display_name TEXT NOT NULL,
    password_salt BLOB NOT NULL,
    password_hash BLOB NOT NULL,
    password_scheme TEXT NOT NULL CHECK (password_scheme = 'scrypt-v1'),
    email_verified INTEGER NOT NULL DEFAULT 0 CHECK (email_verified IN (0, 1)),
    created_at TEXT NOT NULL
);

CREATE TABLE IF NOT EXISTS ranking_lists (
    list_id TEXT PRIMARY KEY,
    title TEXT NOT NULL,
    canonical_path TEXT NOT NULL UNIQUE
);

CREATE TABLE IF NOT EXISTS ranking_items (
    list_id TEXT NOT NULL REFERENCES ranking_lists(list_id) ON DELETE CASCADE,
    rank INTEGER NOT NULL CHECK (rank > 0),
    asin TEXT NOT NULL REFERENCES catalog_products(asin),
    PRIMARY KEY (list_id, rank),
    UNIQUE (list_id, asin)
);

CREATE TABLE IF NOT EXISTS browser_sessions (
    session_digest TEXT PRIMARY KEY,
    reset_epoch INTEGER NOT NULL,
    created_at TEXT NOT NULL,
    account_id INTEGER REFERENCES accounts(account_id) ON DELETE SET NULL,
    delivery_country_code TEXT
);

CREATE TABLE IF NOT EXISTS compare_items (
    compare_line_id TEXT PRIMARY KEY NOT NULL,
    session_digest TEXT NOT NULL REFERENCES browser_sessions(session_digest) ON DELETE CASCADE,
    asin TEXT NOT NULL REFERENCES commerce_offers(asin),
    selection_json TEXT NOT NULL DEFAULT '{}',
    selection_key TEXT NOT NULL,
    position INTEGER NOT NULL CHECK (position BETWEEN 1 AND 4),
    created_at TEXT NOT NULL,
    UNIQUE (session_digest, asin, selection_key),
    UNIQUE (session_digest, position)
);

CREATE TABLE IF NOT EXISTS account_compare_items (
    compare_line_id TEXT PRIMARY KEY NOT NULL,
    account_id INTEGER NOT NULL REFERENCES accounts(account_id) ON DELETE CASCADE,
    asin TEXT NOT NULL REFERENCES commerce_offers(asin),
    selection_json TEXT NOT NULL DEFAULT '{}',
    selection_key TEXT NOT NULL,
    position INTEGER NOT NULL CHECK (position BETWEEN 1 AND 4),
    created_at TEXT NOT NULL,
    UNIQUE (account_id, asin, selection_key),
    UNIQUE (account_id, position)
);

CREATE TABLE IF NOT EXISTS auth_signin_flows (
    session_digest TEXT PRIMARY KEY REFERENCES browser_sessions(session_digest) ON DELETE CASCADE,
    email_normalized TEXT NOT NULL,
    return_to TEXT,
    updated_at TEXT NOT NULL
);

-- Persistent delivery budgets survive replacement of an auth flow. Recipient
-- keys are SHA-256 digests rather than email addresses.
CREATE TABLE IF NOT EXISTS auth_mail_rate_limits (
    purpose TEXT NOT NULL CHECK (purpose IN ('registration', 'password-reset')),
    scope_type TEXT NOT NULL CHECK (scope_type IN ('session', 'recipient', 'account')),
    scope_key TEXT NOT NULL,
    window_started_at INTEGER NOT NULL,
    send_count INTEGER NOT NULL CHECK (send_count >= 0),
    last_sent_at INTEGER NOT NULL,
    PRIMARY KEY (purpose, scope_type, scope_key)
);

-- Registration credentials remain pending until the email one-time code is
-- verified. Password material is already salted/hashed at this stage; the
-- public storefront never stores a pending plaintext password or OTP.
CREATE TABLE IF NOT EXISTS auth_registration_flows (
    pending_id TEXT PRIMARY KEY,
    session_digest TEXT NOT NULL UNIQUE REFERENCES browser_sessions(session_digest) ON DELETE CASCADE,
    email_normalized TEXT NOT NULL,
    display_name TEXT NOT NULL,
    password_salt BLOB NOT NULL,
    password_hash BLOB NOT NULL,
    password_scheme TEXT NOT NULL CHECK (password_scheme = 'scrypt-v1'),
    return_to TEXT,
    code_salt BLOB NOT NULL,
    code_hash BLOB NOT NULL,
    expires_at INTEGER NOT NULL,
    attempts INTEGER NOT NULL DEFAULT 0 CHECK (attempts BETWEEN 0 AND 5),
    created_at INTEGER NOT NULL,
    updated_at INTEGER NOT NULL
);

-- Verification mail is LOCAL_ONLY unless an operator configures SMTP.  The
-- one-time code is never persisted here: only its salt/hash lives in the flow
-- table, while the short-lived cleartext is held by the current process long
-- enough to render the protected local inbox or call the configured provider.
CREATE TABLE IF NOT EXISTS auth_registration_email_outbox (
    email_id INTEGER PRIMARY KEY AUTOINCREMENT,
    pending_id TEXT NOT NULL UNIQUE REFERENCES auth_registration_flows(pending_id) ON DELETE CASCADE,
    recipient TEXT NOT NULL,
    template TEXT NOT NULL CHECK (template = 'registration-verification'),
    status TEXT NOT NULL CHECK (status IN (
        'LOCAL_ONLY', 'SMTP_PENDING', 'SMTP_SENT', 'SMTP_FAILED'
    )),
    is_simulation INTEGER NOT NULL DEFAULT 1 CHECK (is_simulation IN (0, 1)),
    delivery_attempts INTEGER NOT NULL DEFAULT 0 CHECK (delivery_attempts >= 0),
    claim_token TEXT,
    last_error TEXT,
    attempted_at INTEGER,
    sent_at INTEGER,
    created_at INTEGER NOT NULL,
    CHECK (
        (status = 'LOCAL_ONLY' AND is_simulation = 1)
        OR (status <> 'LOCAL_ONLY' AND is_simulation = 0)
    )
);

-- Password reset state is session-bound. account_id is intentionally nullable
-- so unknown identifiers follow the same public flow without receiving mail.
CREATE TABLE IF NOT EXISTS auth_password_reset_flows (
    reset_id TEXT PRIMARY KEY,
    session_digest TEXT NOT NULL UNIQUE REFERENCES browser_sessions(session_digest) ON DELETE CASCADE,
    account_id INTEGER REFERENCES accounts(account_id) ON DELETE CASCADE,
    return_to TEXT,
    code_salt BLOB NOT NULL,
    code_hash BLOB NOT NULL,
    expires_at INTEGER NOT NULL,
    attempts INTEGER NOT NULL DEFAULT 0 CHECK (attempts BETWEEN 0 AND 5),
    verified_at INTEGER,
    created_at INTEGER NOT NULL,
    updated_at INTEGER NOT NULL
);

CREATE UNIQUE INDEX IF NOT EXISTS auth_password_reset_account_unique_idx
    ON auth_password_reset_flows(account_id)
    WHERE account_id IS NOT NULL;

CREATE TABLE IF NOT EXISTS auth_password_reset_email_outbox (
    email_id INTEGER PRIMARY KEY AUTOINCREMENT,
    reset_id TEXT NOT NULL UNIQUE REFERENCES auth_password_reset_flows(reset_id) ON DELETE CASCADE,
    recipient TEXT NOT NULL,
    template TEXT NOT NULL CHECK (template = 'password-reset-verification'),
    status TEXT NOT NULL CHECK (status IN (
        'LOCAL_ONLY', 'SMTP_PENDING', 'SMTP_SENT', 'SMTP_FAILED'
    )),
    is_simulation INTEGER NOT NULL DEFAULT 1 CHECK (is_simulation IN (0, 1)),
    delivery_attempts INTEGER NOT NULL DEFAULT 0 CHECK (delivery_attempts >= 0),
    claim_token TEXT,
    last_error TEXT,
    attempted_at INTEGER,
    sent_at INTEGER,
    created_at INTEGER NOT NULL,
    CHECK (
        (status = 'LOCAL_ONLY' AND is_simulation = 1)
        OR (status <> 'LOCAL_ONLY' AND is_simulation = 0)
    )
);

CREATE TABLE IF NOT EXISTS carts (
    cart_id INTEGER PRIMARY KEY AUTOINCREMENT,
    session_digest TEXT NOT NULL UNIQUE REFERENCES browser_sessions(session_digest) ON DELETE CASCADE,
    created_at TEXT NOT NULL
);

CREATE TABLE IF NOT EXISTS cart_lines (
    line_id TEXT PRIMARY KEY NOT NULL,
    cart_id INTEGER NOT NULL REFERENCES carts(cart_id) ON DELETE CASCADE,
    asin TEXT NOT NULL REFERENCES commerce_offers(asin),
    quantity INTEGER NOT NULL CHECK (quantity BETWEEN 1 AND 30),
    selection_json TEXT NOT NULL DEFAULT '{}',
    selection_key TEXT NOT NULL,
    line_state TEXT NOT NULL DEFAULT 'ACTIVE'
        CHECK (line_state IN ('ACTIVE', 'SAVED')),
    UNIQUE (cart_id, asin, selection_key)
);

-- Authenticated carts are account-owned so they survive sign-out, session
-- rotation, and a later sign-in from another browser session. Legacy anonymous
-- rows remain readable for migration compatibility; public cart mutations are
-- authenticated and do not create new guest cart lines.
CREATE TABLE IF NOT EXISTS account_cart_lines (
    line_id TEXT PRIMARY KEY NOT NULL,
    account_id INTEGER NOT NULL REFERENCES accounts(account_id) ON DELETE CASCADE,
    asin TEXT NOT NULL REFERENCES commerce_offers(asin),
    quantity INTEGER NOT NULL CHECK (quantity BETWEEN 1 AND 30),
    selection_json TEXT NOT NULL DEFAULT '{}',
    selection_key TEXT NOT NULL,
    line_state TEXT NOT NULL DEFAULT 'ACTIVE'
        CHECK (line_state IN ('ACTIVE', 'SAVED')),
    UNIQUE (account_id, asin, selection_key)
);

-- A guest Buy Now intent must survive the sign-in/registration session
-- rotation without being mixed into the shopper's ordinary cart.
CREATE TABLE IF NOT EXISTS pending_buy_now (
    session_digest TEXT PRIMARY KEY
        REFERENCES browser_sessions(session_digest) ON DELETE CASCADE,
    asin TEXT NOT NULL REFERENCES commerce_offers(asin),
    quantity INTEGER NOT NULL CHECK (quantity BETWEEN 1 AND 30),
    selection_json TEXT NOT NULL DEFAULT '{}',
    created_at TEXT NOT NULL
);

CREATE TABLE IF NOT EXISTS addresses (
    address_id INTEGER PRIMARY KEY AUTOINCREMENT,
    account_id INTEGER NOT NULL REFERENCES accounts(account_id) ON DELETE CASCADE,
    full_name TEXT NOT NULL,
    address_line1 TEXT NOT NULL,
    address_line2 TEXT NOT NULL DEFAULT '',
    city TEXT NOT NULL,
    state_region TEXT NOT NULL,
    postal_code TEXT NOT NULL,
    country_code TEXT NOT NULL CHECK (
        length(country_code) = 2 AND country_code = upper(country_code)
    ),
    phone TEXT NOT NULL DEFAULT '',
    is_default INTEGER NOT NULL DEFAULT 0 CHECK (is_default IN (0, 1)),
    is_archived INTEGER NOT NULL DEFAULT 0 CHECK (is_archived IN (0, 1)),
    revision INTEGER NOT NULL DEFAULT 1 CHECK (revision > 0),
    created_at TEXT NOT NULL,
    updated_at TEXT NOT NULL,
    CHECK (is_archived = 0 OR is_default = 0)
);

CREATE TABLE IF NOT EXISTS checkout_sessions (
    checkout_id INTEGER PRIMARY KEY AUTOINCREMENT,
    account_id INTEGER NOT NULL REFERENCES accounts(account_id) ON DELETE CASCADE,
    idempotency_key TEXT NOT NULL,
    checkout_mode TEXT NOT NULL DEFAULT 'CART'
        CHECK (checkout_mode IN ('CART', 'BUY_NOW')),
    status TEXT NOT NULL CHECK (status IN (
        'CART_READY', 'ADDRESS_SELECTED', 'DELIVERY_SELECTED',
        'PAYMENT_SELECTED', 'PAYMENT_PENDING', 'PLACED'
    )),
    address_id INTEGER REFERENCES addresses(address_id),
    delivery_method TEXT CHECK (
        delivery_method IS NULL OR delivery_method IN ('standard', 'expedited')
    ),
    shipping_minor INTEGER CHECK (
        shipping_minor IS NULL OR shipping_minor IN (0, 1299)
    ),
    currency TEXT NOT NULL DEFAULT 'USD',
    created_at TEXT NOT NULL,
    updated_at TEXT NOT NULL,
    placed_at TEXT,
    CHECK (
        (status = 'CART_READY' AND address_id IS NULL
            AND delivery_method IS NULL AND shipping_minor IS NULL
            AND placed_at IS NULL)
        OR
        (status = 'ADDRESS_SELECTED' AND address_id IS NOT NULL
            AND delivery_method IS NULL AND shipping_minor IS NULL
            AND placed_at IS NULL)
        OR
        (status IN ('DELIVERY_SELECTED', 'PAYMENT_SELECTED', 'PAYMENT_PENDING')
            AND address_id IS NOT NULL AND delivery_method IS NOT NULL
            AND shipping_minor IS NOT NULL AND placed_at IS NULL)
        OR
        (status = 'PLACED' AND address_id IS NOT NULL
            AND delivery_method IS NOT NULL AND shipping_minor IS NOT NULL
            AND placed_at IS NOT NULL)
    )
);

CREATE UNIQUE INDEX IF NOT EXISTS checkout_sessions_one_open_account_idx
    ON checkout_sessions(account_id) WHERE status <> 'PLACED';
CREATE UNIQUE INDEX IF NOT EXISTS checkout_sessions_idempotency_key_idx
    ON checkout_sessions(idempotency_key);

-- BUY_NOW checkouts own an isolated line snapshot.  CART checkouts continue
-- to read the account cart so cart edits invalidate stale payment approvals.
CREATE TABLE IF NOT EXISTS checkout_lines (
    checkout_id INTEGER NOT NULL
        REFERENCES checkout_sessions(checkout_id) ON DELETE CASCADE,
    ordinal INTEGER NOT NULL CHECK (ordinal > 0),
    asin TEXT NOT NULL REFERENCES commerce_offers(asin),
    quantity INTEGER NOT NULL CHECK (quantity BETWEEN 1 AND 30),
    selection_json TEXT NOT NULL DEFAULT '{}',
    PRIMARY KEY (checkout_id, ordinal)
);

CREATE TABLE IF NOT EXISTS payment_attempts (
    payment_attempt_id INTEGER PRIMARY KEY AUTOINCREMENT,
    checkout_id INTEGER NOT NULL REFERENCES checkout_sessions(checkout_id) ON DELETE CASCADE,
    account_id INTEGER NOT NULL REFERENCES accounts(account_id) ON DELETE CASCADE,
    method TEXT NOT NULL CHECK (method IN (
        'test-card','sandbox-card-approved','sandbox-card-declined',
        'sandbox-bank-approved','stripe-test'
    )),
    status TEXT NOT NULL CHECK (status IN ('APPROVED', 'DECLINED', 'SUPERSEDED')),
    amount_minor INTEGER NOT NULL CHECK (amount_minor >= 0),
    currency TEXT NOT NULL,
    cart_fingerprint TEXT NOT NULL,
    site_backend_flow_id TEXT,
    site_backend_attempt_id TEXT,
    is_simulation INTEGER NOT NULL DEFAULT 1 CHECK (is_simulation = 1),
    created_at TEXT NOT NULL
);

CREATE UNIQUE INDEX IF NOT EXISTS payment_attempts_one_approved_checkout_idx
    ON payment_attempts(checkout_id) WHERE status = 'APPROVED';

-- Stripe is an opt-in external test profile.  The browser never supplies
-- transaction prices or payment credentials; these rows freeze the exact
-- server quote used to create one hosted Checkout Session.
CREATE TABLE IF NOT EXISTS stripe_payment_sessions (
    stripe_payment_session_id INTEGER PRIMARY KEY AUTOINCREMENT,
    checkout_id INTEGER NOT NULL UNIQUE
        REFERENCES checkout_sessions(checkout_id) ON DELETE CASCADE,
    account_id INTEGER NOT NULL
        REFERENCES accounts(account_id) ON DELETE CASCADE,
    checkout_token TEXT NOT NULL UNIQUE,
    provider_session_id TEXT UNIQUE,
    provider_idempotency_key TEXT NOT NULL UNIQUE,
    site_backend_flow_id TEXT,
    amount_minor INTEGER NOT NULL CHECK (amount_minor >= 0),
    currency TEXT NOT NULL,
    cart_fingerprint TEXT NOT NULL,
    snapshot_hash TEXT NOT NULL,
    shipping_address_json TEXT NOT NULL,
    delivery_method TEXT NOT NULL CHECK (
        delivery_method IN ('standard','expedited')
    ),
    shipping_minor INTEGER NOT NULL CHECK (shipping_minor IN (0,1299)),
    status TEXT NOT NULL CHECK (status IN (
        'CREATING','OPEN','PAID','CANCELLED','EXPIRED','FAILED','INVALID'
    )),
    provider_payment_status TEXT,
    expires_at INTEGER NOT NULL,
    created_at TEXT NOT NULL,
    updated_at TEXT NOT NULL
);

CREATE INDEX IF NOT EXISTS stripe_payment_sessions_provider_idx
    ON stripe_payment_sessions(provider_session_id);

CREATE TABLE IF NOT EXISTS stripe_checkout_lines (
    stripe_payment_session_id INTEGER NOT NULL
        REFERENCES stripe_payment_sessions(stripe_payment_session_id)
        ON DELETE CASCADE,
    ordinal INTEGER NOT NULL CHECK (ordinal > 0),
    asin TEXT NOT NULL,
    title TEXT NOT NULL,
    image_path TEXT NOT NULL,
    quantity INTEGER NOT NULL CHECK (quantity BETWEEN 1 AND 30),
    selection_json TEXT NOT NULL DEFAULT '{}',
    unit_price_minor INTEGER NOT NULL CHECK (unit_price_minor >= 0),
    line_total_minor INTEGER NOT NULL CHECK (
        line_total_minor = unit_price_minor * quantity
    ),
    currency TEXT NOT NULL,
    PRIMARY KEY (stripe_payment_session_id, ordinal)
);

CREATE TABLE IF NOT EXISTS stripe_webhook_events (
    event_id TEXT PRIMARY KEY,
    stripe_payment_session_id INTEGER
        REFERENCES stripe_payment_sessions(stripe_payment_session_id)
        ON DELETE SET NULL,
    event_type TEXT NOT NULL,
    provider_created_at INTEGER NOT NULL,
    status TEXT NOT NULL CHECK (status IN (
        'PROCESSING','PROCESSED','IGNORED','REJECTED'
    )),
    detail TEXT NOT NULL DEFAULT '',
    created_at TEXT NOT NULL,
    processed_at TEXT
);

CREATE TABLE IF NOT EXISTS orders (
    order_id INTEGER PRIMARY KEY AUTOINCREMENT,
    account_id INTEGER NOT NULL REFERENCES accounts(account_id) ON DELETE CASCADE,
    checkout_id INTEGER NOT NULL UNIQUE REFERENCES checkout_sessions(checkout_id),
    payment_attempt_id INTEGER NOT NULL UNIQUE REFERENCES payment_attempts(payment_attempt_id),
    idempotency_key TEXT NOT NULL,
    status TEXT NOT NULL CHECK (status = 'PLACED'),
    items_subtotal_minor INTEGER NOT NULL CHECK (items_subtotal_minor >= 0),
    shipping_minor INTEGER NOT NULL CHECK (shipping_minor IN (0, 1299)),
    total_minor INTEGER NOT NULL CHECK (
        total_minor >= 0 AND total_minor = items_subtotal_minor + shipping_minor
    ),
    currency TEXT NOT NULL,
    delivery_method TEXT NOT NULL CHECK (
        delivery_method IN ('standard', 'expedited')
    ),
    shipping_address_json TEXT NOT NULL,
    is_simulation INTEGER NOT NULL DEFAULT 1 CHECK (is_simulation = 1),
    created_at TEXT NOT NULL,
    UNIQUE (account_id, idempotency_key)
);

CREATE INDEX IF NOT EXISTS orders_account_created_idx
    ON orders(account_id, order_id DESC);

CREATE TABLE IF NOT EXISTS order_items (
    order_item_id INTEGER PRIMARY KEY AUTOINCREMENT,
    order_id INTEGER NOT NULL REFERENCES orders(order_id) ON DELETE CASCADE,
    ordinal INTEGER NOT NULL CHECK (ordinal > 0),
    asin TEXT NOT NULL,
    title TEXT NOT NULL,
    image_path TEXT NOT NULL,
    quantity INTEGER NOT NULL CHECK (quantity BETWEEN 1 AND 30),
    selection_json TEXT NOT NULL DEFAULT '{}',
    unit_price_minor INTEGER NOT NULL CHECK (unit_price_minor >= 0),
    line_total_minor INTEGER NOT NULL CHECK (
        line_total_minor = unit_price_minor * quantity
    ),
    currency TEXT NOT NULL,
    UNIQUE (order_id, ordinal)
);

CREATE TABLE IF NOT EXISTS shipments (
    shipment_id INTEGER PRIMARY KEY AUTOINCREMENT,
    order_id INTEGER NOT NULL UNIQUE REFERENCES orders(order_id) ON DELETE CASCADE,
    status TEXT NOT NULL CHECK (status = 'PREPARING'),
    lifecycle_status TEXT NOT NULL DEFAULT 'PREPARING' CHECK (
        lifecycle_status IN ('PREPARING', 'SHIPPED', 'DELIVERED', 'CANCELLED')
    ),
    revision INTEGER NOT NULL DEFAULT 1 CHECK (revision > 0),
    delivery_method TEXT NOT NULL CHECK (
        delivery_method IN ('standard', 'expedited')
    ),
    shipping_minor INTEGER NOT NULL CHECK (shipping_minor IN (0, 1299)),
    carrier TEXT NOT NULL,
    tracking_code TEXT,
    is_simulation INTEGER NOT NULL DEFAULT 1 CHECK (is_simulation = 1),
    created_at TEXT NOT NULL,
    updated_at TEXT NOT NULL,
    shipped_at TEXT,
    delivered_at TEXT,
    cancelled_at TEXT,
    CHECK (
        (lifecycle_status IN ('PREPARING', 'CANCELLED') AND tracking_code IS NULL)
        OR
        (lifecycle_status IN ('SHIPPED', 'DELIVERED') AND tracking_code IS NOT NULL
            AND length(tracking_code) BETWEEN 8 AND 64)
    ),
    CHECK (lifecycle_status<>'SHIPPED' OR shipped_at IS NOT NULL),
    CHECK (lifecycle_status<>'DELIVERED' OR (shipped_at IS NOT NULL AND delivered_at IS NOT NULL)),
    CHECK (lifecycle_status<>'CANCELLED' OR cancelled_at IS NOT NULL)
);

CREATE TABLE IF NOT EXISTS order_events (
    order_event_id INTEGER PRIMARY KEY AUTOINCREMENT,
    order_id INTEGER NOT NULL REFERENCES orders(order_id) ON DELETE CASCADE,
    account_id INTEGER NOT NULL REFERENCES accounts(account_id) ON DELETE CASCADE,
    event_type TEXT NOT NULL CHECK (event_type IN (
        'ORDER_PLACED', 'ORDER_CANCELLED', 'SHIPMENT_SHIPPED',
        'SHIPMENT_DELIVERED', 'RETURN_REQUESTED', 'RETURN_RECEIVED',
        'RETURN_REFUNDED'
    )),
    actor TEXT NOT NULL CHECK (actor IN ('CUSTOMER', 'ADMIN', 'SYSTEM')),
    from_status TEXT,
    to_status TEXT NOT NULL,
    idempotency_key TEXT,
    detail_json TEXT NOT NULL DEFAULT '{}',
    created_at TEXT NOT NULL,
    UNIQUE (order_id, event_type)
);

CREATE INDEX IF NOT EXISTS order_events_order_idx
    ON order_events(order_id, order_event_id);
CREATE UNIQUE INDEX IF NOT EXISTS order_events_mutation_key_idx
    ON order_events(account_id, event_type, idempotency_key)
    WHERE idempotency_key IS NOT NULL;

CREATE TABLE IF NOT EXISTS order_action_keys (
    order_action_key_id INTEGER PRIMARY KEY AUTOINCREMENT,
    account_id INTEGER NOT NULL REFERENCES accounts(account_id) ON DELETE CASCADE,
    order_id INTEGER NOT NULL REFERENCES orders(order_id) ON DELETE CASCADE,
    action_type TEXT NOT NULL CHECK (action_type IN ('CANCEL', 'RETURN_REQUEST')),
    idempotency_key TEXT NOT NULL,
    result_reference INTEGER,
    created_at TEXT NOT NULL,
    UNIQUE (account_id, action_type, idempotency_key),
    UNIQUE (order_id, action_type)
);

CREATE TABLE IF NOT EXISTS return_requests (
    return_request_id INTEGER PRIMARY KEY AUTOINCREMENT,
    account_id INTEGER NOT NULL REFERENCES accounts(account_id) ON DELETE CASCADE,
    order_id INTEGER NOT NULL UNIQUE REFERENCES orders(order_id) ON DELETE CASCADE,
    idempotency_key TEXT NOT NULL,
    reason_code TEXT NOT NULL CHECK (reason_code IN (
        'DAMAGED', 'DEFECTIVE', 'NOT_AS_DESCRIBED',
        'WRONG_ITEM', 'NO_LONGER_NEEDED'
    )),
    customer_note TEXT NOT NULL DEFAULT '' CHECK (length(customer_note) <= 500),
    status TEXT NOT NULL CHECK (status IN ('REQUESTED', 'RECEIVED', 'REFUNDED')),
    revision INTEGER NOT NULL DEFAULT 1 CHECK (revision > 0),
    is_simulation INTEGER NOT NULL DEFAULT 1 CHECK (is_simulation = 1),
    created_at TEXT NOT NULL,
    updated_at TEXT NOT NULL,
    UNIQUE (account_id, idempotency_key)
);

CREATE INDEX IF NOT EXISTS return_requests_account_idx
    ON return_requests(account_id, return_request_id DESC);

CREATE TABLE IF NOT EXISTS return_request_items (
    return_request_id INTEGER NOT NULL
        REFERENCES return_requests(return_request_id) ON DELETE CASCADE,
    order_item_id INTEGER NOT NULL REFERENCES order_items(order_item_id),
    quantity INTEGER NOT NULL CHECK (quantity > 0),
    PRIMARY KEY (return_request_id, order_item_id)
);

CREATE TABLE IF NOT EXISTS refunds (
    refund_id INTEGER PRIMARY KEY AUTOINCREMENT,
    account_id INTEGER NOT NULL REFERENCES accounts(account_id) ON DELETE CASCADE,
    order_id INTEGER NOT NULL REFERENCES orders(order_id) ON DELETE CASCADE,
    payment_attempt_id INTEGER NOT NULL REFERENCES payment_attempts(payment_attempt_id),
    return_request_id INTEGER REFERENCES return_requests(return_request_id) ON DELETE CASCADE,
    kind TEXT NOT NULL CHECK (kind IN ('CANCELLATION', 'RETURN')),
    status TEXT NOT NULL CHECK (status = 'COMPLETED'),
    amount_minor INTEGER NOT NULL CHECK (amount_minor >= 0),
    currency TEXT NOT NULL,
    idempotency_key TEXT NOT NULL,
    is_simulation INTEGER NOT NULL DEFAULT 1 CHECK (is_simulation = 1),
    created_at TEXT NOT NULL,
    CHECK (
        (kind='CANCELLATION' AND return_request_id IS NULL)
        OR (kind='RETURN' AND return_request_id IS NOT NULL)
    ),
    UNIQUE (order_id, kind),
    UNIQUE (account_id, idempotency_key)
);

CREATE INDEX IF NOT EXISTS refunds_account_idx
    ON refunds(account_id, refund_id DESC);

CREATE TABLE IF NOT EXISTS email_outbox (
    email_id INTEGER PRIMARY KEY AUTOINCREMENT,
    account_id INTEGER NOT NULL REFERENCES accounts(account_id) ON DELETE CASCADE,
    order_id INTEGER NOT NULL UNIQUE REFERENCES orders(order_id) ON DELETE CASCADE,
    recipient TEXT NOT NULL,
    template TEXT NOT NULL CHECK (template = 'order-confirmation'),
    subject TEXT NOT NULL,
    payload_json TEXT NOT NULL,
    site_backend_mail_id TEXT,
    site_backend_claim_token TEXT,
    status TEXT NOT NULL CHECK (status IN (
        'LOCAL_ONLY', 'SMTP_PENDING', 'SMTP_SENT', 'SMTP_FAILED'
    )),
    is_simulation INTEGER NOT NULL DEFAULT 1 CHECK (is_simulation IN (0, 1)),
    delivery_attempts INTEGER NOT NULL DEFAULT 0 CHECK (delivery_attempts >= 0),
    claim_token TEXT,
    last_error TEXT,
    attempted_at INTEGER,
    sent_at INTEGER,
    created_at TEXT NOT NULL,
    CHECK (
        (status = 'LOCAL_ONLY' AND is_simulation = 1)
        OR (status <> 'LOCAL_ONLY' AND is_simulation = 0)
    )
);

CREATE TABLE IF NOT EXISTS navigation_events (
    event_id INTEGER PRIMARY KEY AUTOINCREMENT,
    session_digest TEXT NOT NULL REFERENCES browser_sessions(session_digest) ON DELETE CASCADE,
    sequence INTEGER NOT NULL,
    method TEXT NOT NULL,
    route_key TEXT NOT NULL,
    path TEXT NOT NULL,
    referer TEXT NOT NULL,
    status INTEGER NOT NULL,
    asin TEXT,
    rank INTEGER,
    created_at TEXT NOT NULL,
    UNIQUE (session_digest, sequence)
);

CREATE TABLE IF NOT EXISTS task_progress (
    session_digest TEXT PRIMARY KEY REFERENCES browser_sessions(session_digest) ON DELETE CASCADE,
    task_id TEXT NOT NULL,
    stage TEXT NOT NULL,
    best_sellers_event_id INTEGER REFERENCES navigation_events(event_id),
    pdp_event_id INTEGER REFERENCES navigation_events(event_id),
    flow_capability_digest TEXT,
    capability_consumed INTEGER NOT NULL DEFAULT 0 CHECK (capability_consumed IN (0, 1)),
    reset_epoch INTEGER NOT NULL,
    updated_at TEXT NOT NULL
);

CREATE TABLE IF NOT EXISTS request_journal (
    request_id INTEGER PRIMARY KEY AUTOINCREMENT,
    session_digest TEXT NOT NULL,
    method TEXT NOT NULL,
    path TEXT NOT NULL,
    media_type TEXT NOT NULL,
    raw_body_sha256 TEXT NOT NULL,
    canonical_form TEXT NOT NULL,
    status INTEGER NOT NULL,
    outcome TEXT NOT NULL,
    contract_id TEXT NOT NULL,
    created_at TEXT NOT NULL
);

CREATE TABLE IF NOT EXISTS task_completions (
    completion_id INTEGER PRIMARY KEY AUTOINCREMENT,
    run_id TEXT NOT NULL,
    session_digest TEXT NOT NULL,
    task_id TEXT NOT NULL,
    terminal_path TEXT NOT NULL,
    request_id INTEGER NOT NULL REFERENCES request_journal(request_id),
    completed_at TEXT NOT NULL,
    UNIQUE (run_id, session_digest, task_id)
);

CREATE INDEX IF NOT EXISTS navigation_events_session_idx
    ON navigation_events(session_digest, sequence);
CREATE INDEX IF NOT EXISTS request_journal_session_idx
    ON request_journal(session_digest, request_id);