-- =============================================================================
-- PRODUCTION SEED — chat.applications / chat.api_keys / chat.knowledge_entries
-- Run against: chat_bot (production), AFTER migrations 001-006 have been applied.
-- Idempotent — safe to re-run (upserts on the same fixed ids).
--
-- This mirrors chat-service/prisma/seed.ts, but with real production values
-- instead of the dev-only demo key and localhost allowedOrigins:
--   - allowedOrigins widened to the real forgestack.in domains that embed
--     the widget (see docs/08-deployment.md's reverse-proxy table).
--   - api_keys gets a FRESH, real key — not the hardcoded dev key
--     ('cbk_dead...') the seed script ships for local testing only.
--
-- ⚠ The raw key below is shown ONCE, here, because this file is the delivery
-- mechanism instead of the normal POST /applications/:id/api-keys response.
-- After running this, put the raw key into
-- user-dashboard/src/environments/environment.prod.ts's chatApiKey (and
-- rebuild/redeploy user-dashboard) — the database only ever stores its hash.
--
-- Raw key (put this in environment.prod.ts, then treat this file as sensitive):
--   cbk_bf4542bbe3915a776ce9244bf9baea8f66faa1245a8049ef0491feb14a812623
-- =============================================================================

BEGIN;

-- ---------------------------------------------------------------------------
-- 1) Application — reuses the same id/slug as the dev seed so this lines up
--    whether or not chat-service's seed.ts was ever run against this DB
--    before. externalStoreId = 'store_demo' matches the real (only) store
--    row this platform currently runs — see prisma/seed.ts DEMO_STORE_ID.
-- ---------------------------------------------------------------------------

-- Note: externalStoreId is the one field on Application that maps to a
-- snake_case column (@map("external_store_id") in schema.prisma) — every
-- other column here is camelCase as-is.
INSERT INTO "chat"."applications"
    ("id", "slug", "name", "allowedOrigins", "external_store_id", "updatedBy", "updatedOn")
VALUES
    (
        'app_demo_store',
        'demo-store',
        'Demo Store',
        ARRAY[
            'https://sp-web.forgestack.in',
            'https://sp-account.forgestack.in',
            'https://sp-admin.forgestack.in',
            'https://sp-chat-widget.forgestack.in'
        ]::TEXT[],
        'store_demo',
        'system',
        CURRENT_TIMESTAMP
    )
ON CONFLICT ("id") DO UPDATE SET
    "allowedOrigins"     = EXCLUDED."allowedOrigins",
    "external_store_id"  = EXCLUDED."external_store_id",
    "updatedBy"          = 'system',
    "updatedOn"          = CURRENT_TIMESTAMP;

-- ---------------------------------------------------------------------------
-- 2) API key — SHA-256 hash of the raw key printed in the header comment
--    above. Generated fresh for this deploy, not the seed script's dev key.
-- ---------------------------------------------------------------------------

INSERT INTO "chat"."api_keys"
    ("id", "applicationId", "keyHash", "label", "updatedBy", "updatedOn")
VALUES
    (
        'apikey_prod_2026_08',
        'app_demo_store',
        '4e78476dcb40ea177c69d893ca237a05fd7ce5181380264e781fcc3aed90dc01',
        'production',
        'system',
        CURRENT_TIMESTAMP
    )
ON CONFLICT ("id") DO UPDATE SET
    "keyHash"   = EXCLUDED."keyHash",
    "label"     = EXCLUDED."label",
    "revokedAt" = NULL,
    "updatedBy" = 'system',
    "updatedOn" = CURRENT_TIMESTAMP;

-- Optional cleanup — revoke the dev-only demo key if it was ever seeded here.
-- Harmless no-op if it was never inserted in this database.
UPDATE "chat"."api_keys"
SET "revokedAt" = CURRENT_TIMESTAMP, "updatedBy" = 'system', "updatedOn" = CURRENT_TIMESTAMP
WHERE "id" = 'apikey_demo_store' AND "revokedAt" IS NULL;

-- ---------------------------------------------------------------------------
-- 3) Knowledge base — full 22-entry FAQ content, matching
--    chat-service/prisma/seed.ts's upsertKnowledge() exactly.
-- ---------------------------------------------------------------------------

INSERT INTO "chat"."knowledge_entries"
    ("id", "applicationId", "question", "answer", "keywords", "links", "sortOrder", "updatedBy", "updatedOn")
VALUES
    ('kb_demo_tracking', 'app_demo_store',
     'How do I track my order?',
     'Sign in and open My Account → Orders to see the status of every order you''ve placed, including how many are still pending.',
     ARRAY['track','tracking','order status','where is my order','pending','pending orders','how many orders']::TEXT[],
     '[{"label":"Go to Orders","url":"https://sp-account.forgestack.in/orders"}]'::jsonb, 10, 'system', CURRENT_TIMESTAMP),

    ('kb_demo_order_status', 'app_demo_store',
     'What do the order statuses mean?',
     'Your order moves through Placed → Processing → Shipped → Out for Delivery → Delivered (or Cancelled if something went wrong) — My Account → Orders shows which stage yours is at.',
     ARRAY['order status meaning','what does processing mean','what does shipped mean','status meaning','order stages','out for delivery']::TEXT[],
     '[{"label":"Go to Orders","url":"https://sp-account.forgestack.in/orders"}]'::jsonb, 15, 'system', CURRENT_TIMESTAMP),

    ('kb_demo_wrong_item', 'app_demo_store',
     'I received the wrong or damaged item',
     'Sorry about that — reach out through your account with your order number and a photo, and we''ll arrange a replacement or return.',
     ARRAY['wrong item','damaged item','broken item','received wrong','defective','item damaged']::TEXT[],
     '[{"label":"Go to Orders","url":"https://sp-account.forgestack.in/orders"}]'::jsonb, 45, 'system', CURRENT_TIMESTAMP),

    ('kb_demo_payment', 'app_demo_store',
     'What payment methods do you accept?',
     'We accept Cash on Delivery and online payments via Razorpay (cards, UPI, netbanking) — pick whichever you like at checkout.',
     ARRAY['payment','pay','cod','cash on delivery','card','upi']::TEXT[],
     '[{"label":"Go to Checkout","url":"https://sp-web.forgestack.in/checkout"}]'::jsonb, 20, 'system', CURRENT_TIMESTAMP),

    ('kb_demo_card_storage', 'app_demo_store',
     'Do you store my card details?',
     'No — card and UPI payments are processed securely by Razorpay; we never see or store your card details.',
     ARRAY['store card','card details','save card','card security','is it safe to pay','card safety']::TEXT[],
     '[]'::jsonb, 25, 'system', CURRENT_TIMESTAMP),

    ('kb_demo_payment_failed', 'app_demo_store',
     'My payment failed but money was deducted',
     'That''s usually your bank or UPI app auto-reversing the hold — it typically resolves within a few days. If it doesn''t, contact us with the payment reference and we''ll help sort it out.',
     ARRAY['payment failed','money deducted','amount deducted','payment deducted but failed','failed transaction','debited but failed']::TEXT[],
     '[]'::jsonb, 26, 'system', CURRENT_TIMESTAMP),

    ('kb_demo_cancel', 'app_demo_store',
     'Can I cancel or change my order?',
     'Contact us as soon as possible through your account — orders that haven''t shipped yet can usually be changed or cancelled.',
     ARRAY['cancel','change order','modify order']::TEXT[],
     '[{"label":"Go to Orders","url":"https://sp-account.forgestack.in/orders"}]'::jsonb, 30, 'system', CURRENT_TIMESTAMP),

    ('kb_demo_returns', 'app_demo_store',
     'What is your return policy?',
     'If something isn''t right with your order, reach out through your account and we''ll help arrange a return or replacement.',
     ARRAY['return','refund','exchange']::TEXT[],
     '[{"label":"Go to Orders","url":"https://sp-account.forgestack.in/orders"}]'::jsonb, 40, 'system', CURRENT_TIMESTAMP),

    ('kb_demo_shipping', 'app_demo_store',
     'Do you offer free shipping?',
     'Yes — orders above ₹199 ship for free; smaller orders have a flat delivery fee. Check your cart to see it applied.',
     ARRAY['shipping','delivery','free shipping']::TEXT[],
     '[{"label":"View Cart","url":"https://sp-web.forgestack.in/cart"}]'::jsonb, 50, 'system', CURRENT_TIMESTAMP),

    ('kb_demo_delivery_time', 'app_demo_store',
     'How long does delivery take?',
     'Delivery time depends on your location and courier — you''ll see an estimate at checkout before you place your order.',
     ARRAY['delivery time','how long delivery','when will it arrive','shipping time','estimated delivery','how many days delivery']::TEXT[],
     '[]'::jsonb, 55, 'system', CURRENT_TIMESTAMP),

    ('kb_demo_delivery_areas', 'app_demo_store',
     'Which areas do you deliver to?',
     'Enter your address at checkout to confirm we deliver to your pin code.',
     ARRAY['delivery areas','do you deliver to','delivery locations','pin code','serviceable area','deliver to my city']::TEXT[],
     '[{"label":"View Cart","url":"https://sp-web.forgestack.in/cart"}]'::jsonb, 56, 'system', CURRENT_TIMESTAMP),

    ('kb_demo_coupon', 'app_demo_store',
     'How do I apply a discount code?',
     'Enter your code in the "Apply coupon" field on the cart page before checking out.',
     ARRAY['coupon','discount','promo code','code']::TEXT[],
     '[{"label":"Go to Cart","url":"https://sp-web.forgestack.in/cart"}]'::jsonb, 60, 'system', CURRENT_TIMESTAMP),

    ('kb_demo_coupon_not_working', 'app_demo_store',
     'Why isn''t my coupon code working?',
     'Check that it hasn''t expired, your order meets its minimum amount, it hasn''t hit its usage limit, and — for new-customer codes — that you haven''t ordered with us before.',
     ARRAY['coupon not working','discount code not working','coupon invalid','code expired','coupon error','coupon rejected']::TEXT[],
     '[]'::jsonb, 65, 'system', CURRENT_TIMESTAMP),

    ('kb_demo_coupon_stacking', 'app_demo_store',
     'Can I use more than one coupon at once?',
     'Only if every code you''re combining is marked stackable — otherwise applying a new code just replaces the old one.',
     ARRAY['multiple coupons','stack coupons','combine discount codes','more than one coupon','two coupons']::TEXT[],
     '[]'::jsonb, 66, 'system', CURRENT_TIMESTAMP),

    ('kb_demo_forgot_password', 'app_demo_store',
     'I forgot my password',
     'Use the "Forgot password" link on the sign-in page to reset it by email.',
     ARRAY['forgot password','reset password','cant login','cant sign in','password reset','locked out']::TEXT[],
     '[{"label":"Reset Password","url":"https://sp-web.forgestack.in/forgot-password"}]'::jsonb, 70, 'system', CURRENT_TIMESTAMP),

    ('kb_demo_create_account', 'app_demo_store',
     'How do I create an account?',
     'Tap Sign Up on the login page and fill in your details — you''ll get a verification email to confirm it.',
     ARRAY['create account','sign up','register','new account','how to register']::TEXT[],
     '[{"label":"Create Account","url":"https://sp-web.forgestack.in/register"}]'::jsonb, 71, 'system', CURRENT_TIMESTAMP),

    ('kb_demo_multi_store_account', 'app_demo_store',
     'Can I use the same account at more than one store?',
     'Yes — one login works everywhere. The first time you sign in at a new store, you''re automatically added there — no separate account needed.',
     ARRAY['multiple stores','same account different store','one account many stores','switch store','shop at another store']::TEXT[],
     '[]'::jsonb, 72, 'system', CURRENT_TIMESTAMP),

    ('kb_demo_verification_email', 'app_demo_store',
     'I didn''t get my verification email',
     'Check your spam folder first — if it''s still not there, use the resend-verification option on the sign-in/register page.',
     ARRAY['verification email','no verification email','resend verification','confirm email','email not received']::TEXT[],
     '[]'::jsonb, 73, 'system', CURRENT_TIMESTAMP),

    ('kb_demo_addresses', 'app_demo_store',
     'How do I add or manage delivery addresses?',
     'Open My Account → Addresses to add, edit, or remove your saved delivery addresses.',
     ARRAY['add address','edit address','manage address','delivery address','saved addresses','change address']::TEXT[],
     '[{"label":"Go to Addresses","url":"https://sp-account.forgestack.in/addresses"}]'::jsonb, 80, 'system', CURRENT_TIMESTAMP),

    ('kb_demo_wishlist', 'app_demo_store',
     'How do I save an item for later?',
     'Tap the heart icon on any product to add it to your Wishlist — find it anytime under My Account → Wishlist.',
     ARRAY['save for later','wishlist','favorite item','heart icon','save item']::TEXT[],
     '[{"label":"Go to Wishlist","url":"https://sp-account.forgestack.in/wishlist"}]'::jsonb, 81, 'system', CURRENT_TIMESTAMP),

    ('kb_demo_reviews', 'app_demo_store',
     'How do I leave a product review?',
     'Once an order has been delivered, you can leave a 1-5 star review from that order or the product page.',
     ARRAY['leave a review','write a review','rate a product','product review','rating','review a product']::TEXT[],
     '[]'::jsonb, 90, 'system', CURRENT_TIMESTAMP),

    ('kb_demo_out_of_stock', 'app_demo_store',
     'Why is an item showing out of stock?',
     'The seller is temporarily out — it''ll reappear if restocked, but we can''t guarantee a timeline. Stock and price can change by the time you check out, even for items already in your cart.',
     ARRAY['out of stock','unavailable','item unavailable','sold out','restock','stock unavailable']::TEXT[],
     '[]'::jsonb, 95, 'system', CURRENT_TIMESTAMP)

ON CONFLICT ("id") DO UPDATE SET
    "question"  = EXCLUDED."question",
    "answer"    = EXCLUDED."answer",
    "keywords"  = EXCLUDED."keywords",
    "links"     = EXCLUDED."links",
    "sortOrder" = EXCLUDED."sortOrder",
    "updatedBy" = 'system',
    "updatedOn" = CURRENT_TIMESTAMP;

COMMIT;
