-- ============================================================================
-- Dabil — Organisation module fix
-- Run once on the Dabil database. Safe to re-run.
--
-- Root cause: the users.role ENUM shipped without 'org_admin' / 'org_staff',
-- so organisation accounts were saved with an empty role — they couldn't log
-- in, didn't show up in staff lists, and never got the wallets the insert
-- trigger creates for org_staff. The app now also self-heals this on the org
-- login / organisations pages, but running this once cleans everything up.
-- ============================================================================

-- 1) Add the organisation roles to the ENUM.
ALTER TABLE `users`
  MODIFY COLUMN `role`
  ENUM('super_admin','restaurant_admin','staff','waiter','customer','org_admin','org_staff')
  NOT NULL DEFAULT 'customer';

-- 2) Repair accounts that were saved with a blank role.
--    Staff carry an employee_id or department; the org admin has neither.
UPDATE `users` SET `role` = 'org_staff'
 WHERE (`role` = '' OR `role` IS NULL) AND `organization_id` IS NOT NULL
   AND ((`employee_id` IS NOT NULL AND `employee_id` <> '')
        OR (`department` IS NOT NULL AND `department` <> ''));

UPDATE `users` SET `role` = 'org_admin'
 WHERE (`role` = '' OR `role` IS NULL) AND `organization_id` IS NOT NULL;

-- 3) Backfill the wallets the insert-trigger would have created for staff.
INSERT INTO `wallets` (`user_id`, `wallet_type`, `balance`, `created_at`)
SELECT u.`id`, 'customer', 0.00, NOW() FROM `users` u
 WHERE u.`role` = 'org_staff'
   AND NOT EXISTS (SELECT 1 FROM `wallets` w WHERE w.`user_id` = u.`id` AND w.`wallet_type` = 'customer');

INSERT INTO `wallets` (`user_id`, `wallet_type`, `organization_id`, `balance`, `created_at`)
SELECT u.`id`, 'meal_ticket', u.`organization_id`, 0.00, NOW() FROM `users` u
 WHERE u.`role` = 'org_staff'
   AND NOT EXISTS (SELECT 1 FROM `wallets` w WHERE w.`user_id` = u.`id` AND w.`wallet_type` = 'meal_ticket');
