-- =============================================================================
-- MIGRATION: Backfill default GST tax slabs for every store missing them
--
-- TaxSlabProfile is per-store (@@unique([storeId, code])) — until now, only
-- store_demo ever got the 5 canonical Indian GST slabs (prisma/seed.ts's
-- GST_SLABS), because MerchantService.createStore() never provisioned any
-- default data for a merchant's own store. Every store created via
-- self-serve merchant registration landed with a genuinely empty Tax
-- Management -> Tax Slab Profiles page.
--
-- This is a one-time backfill for stores that already exist.
-- MerchantService.createStore() is also fixed going forward so newly
-- created stores get these at creation time and never need this backfill.
--
-- Run: idempotent — safe to re-execute. Skips any store+code pair that
-- already exists, so a store with some but not all 5 (e.g. one an admin
-- manually added a custom slab to) only gets the ones it's missing.
-- =============================================================================

BEGIN;

INSERT INTO master.tax_slab_profiles
  (id, "storeId", code, name, "hsnGroup", "igstRateBps", "cgstRateBps", "sgstRateBps", "createdBy", "updatedBy")
SELECT
  gen_random_uuid()::text, s.id, slab.code, slab.name, slab."hsnGroup", slab.igst, slab.cgst, slab.sgst,
  'system:tax-slab-backfill', 'system:tax-slab-backfill'
FROM store.stores s
CROSS JOIN (VALUES
  ('gst-zero-rated',     'GST Zero-Rated',     'Essential Items',                0,    0,    0),
  ('gst-apparel-low',    'GST Apparel Low',    'Garments < ₹1000',               500,  250,  250),
  ('gst-standard-1',     'GST Standard 1',     'Mass Consumer Goods',            1200, 600,  600),
  ('gst-standard-2',     'GST Standard 2',     'Electronics / General Services', 1800, 900,  900),
  ('gst-luxury-demerit', 'GST Luxury/Demerit', 'Automobiles / Luxury Tech',      2800, 1400, 1400)
) AS slab(code, name, "hsnGroup", igst, cgst, sgst)
WHERE s."deletedAt" IS NULL
  AND NOT EXISTS (
    SELECT 1 FROM master.tax_slab_profiles existing
    WHERE existing."storeId" = s.id AND existing.code = slab.code
  );

COMMIT;

-- Verify — every non-deleted store should show 5 (or more, if it already had
-- custom slabs on top of these)
SELECT s.name AS store, COUNT(t.id) AS tax_slab_count
FROM store.stores s
LEFT JOIN master.tax_slab_profiles t ON t."storeId" = s.id
WHERE s."deletedAt" IS NULL
GROUP BY s.id, s.name
ORDER BY s.name;
