INSERT INTO credit_accounts (owner_type, owner_id, currency, balance_cached)
SELECT 'user', 2, 'EUR', 250.00
WHERE NOT EXISTS (
    SELECT 1 FROM credit_accounts WHERE owner_type = 'user' AND owner_id = 2
);

INSERT INTO credit_transactions (account_id, movement_type, amount, reference, reason, created_by_user_id)
SELECT ca.id, 'grant', 250.00, 'SEED-INIT', 'Crédit commercial initial', 1
FROM credit_accounts ca
WHERE ca.owner_type = 'user'
  AND ca.owner_id = 2
  AND NOT EXISTS (
      SELECT 1 FROM credit_transactions ct WHERE ct.account_id = ca.id AND ct.reference = 'SEED-INIT'
  );

INSERT INTO orders (
    shop_id, user_id, order_number, status,
    billing_address_json, shipping_address_json,
    subtotal_ht, credit_used_ht, total_ht, total_ttc,
    submitted_at, fulfilled_at
)
SELECT
    2,
    2,
    'ORD-000001',
    'submitted',
    JSON_OBJECT('company', 'Franchise A', 'line1', '8 avenue du Commerce', 'postal_code', '69001', 'city', 'Lyon', 'country', 'FR'),
    JSON_OBJECT('company', 'Franchise A', 'line1', '8 avenue du Commerce', 'postal_code', '69001', 'city', 'Lyon', 'country', 'FR'),
    120.00,
    20.00,
    100.00,
    120.00,
    NOW(),
    NULL
WHERE NOT EXISTS (SELECT 1 FROM orders WHERE order_number = 'ORD-000001');

INSERT INTO order_items (
    order_id, source_product_id, shop_product_id, label, quantity,
    unit_nominal_ht, applied_coefficient, unit_sale_ht, line_total_ht, configuration_json
)
SELECT
    o.id,
    1,
    (
        SELECT sp.id
        FROM shop_products sp
        WHERE sp.shop_id = 2 AND sp.source_product_id = 1
        ORDER BY sp.id ASC
        LIMIT 1
    ),
    'Flyers A5 - 500 ex',
    1,
    80.00,
    1.5000,
    120.00,
    120.00,
    JSON_OBJECT('format', 'A5', 'quantite_du_lot', '500')
FROM orders o
WHERE o.order_number = 'ORD-000001'
  AND NOT EXISTS (
      SELECT 1 FROM order_items oi WHERE oi.order_id = o.id
  );

INSERT INTO order_status_history (order_id, from_status, to_status, comment, created_by_user_id)
SELECT o.id, NULL, 'submitted', 'Commande de démonstration', 1
FROM orders o
WHERE o.order_number = 'ORD-000001'
  AND NOT EXISTS (
      SELECT 1 FROM order_status_history osh WHERE osh.order_id = o.id
  );
