-- 053_point_user_storeid_at_own_store.sql
--
-- Points `admin.users.storeId` at a store the user can actually administer.
--
-- The column carries `@default("store_demo")`, so every self-registered
-- merchant kept that placeholder for ever — nothing set it when their store was
-- created. The admin frontend reads it to pick the active store and sends it as
-- `x-store-id`, so every request went out claiming the demo store, which the
-- merchant holds no StoreStaff row for. AdminAccessGuard refused all of them:
-- "Admin access is required" on /admin/templates, /admin/email-settings,
-- /admin/readiness — every store-scoped screen in the product.
--
-- Seeded merchants were unaffected because the seed set a real storeId, which
-- is exactly why this stayed invisible in testing.
--
-- Conservative: only rewrites the value when the user is NOT active staff of
-- the store it currently names, and only ever points it at a store they ARE
-- active staff of. A deliberate selection is never overwritten.

BEGIN;

UPDATE admin.users u
   SET "storeId"  = own."storeId",
       "updatedBy" = 'system:repair-053',
       "updatedOn" = now()
  FROM (
    SELECT st."userId", st."storeId",
           row_number() OVER (PARTITION BY st."userId" ORDER BY s."createdOn") AS rn
      FROM store.store_staff st
      JOIN store.stores s ON s."id" = st."storeId"
     WHERE st."isActive" AND s."isActive" AND s."deletedAt" IS NULL
  ) own
 WHERE own."userId" = u."id"
   AND own.rn = 1
   -- Only when the current value is unusable to them.
   AND NOT EXISTS (
     SELECT 1 FROM store.store_staff cur
      WHERE cur."userId" = u."id"
        AND cur."storeId" = u."storeId"
        AND cur."isActive"
   );

DO $$
DECLARE broken INT;
BEGIN
  SELECT count(*) INTO broken
    FROM admin.users u
   WHERE u."role" = 'merchant'
     AND NOT EXISTS (
       SELECT 1 FROM store.store_staff st
        WHERE st."userId" = u."id" AND st."storeId" = u."storeId" AND st."isActive"
     );

  IF broken > 0 THEN
    RAISE NOTICE 'repair-053: % merchant(s) still point at a store they cannot access (they have no active staff row anywhere)', broken;
  ELSE
    RAISE NOTICE 'repair-053: every merchant now points at a store they can administer';
  END IF;
END $$;

COMMIT;
