/**
 * User Role Assignment Script
 * 
 * Purpose: Assign roles to specific users after fresh database setup
 * 
 * Usage:
 * 1. Update the email addresses below with your actual users
 * 2. Run: psql -d royal_enfield_workflow -f scripts/assign-user-roles.sql
 * 
 * Roles:
 * - USER: Default role for all employees
 * - MANAGEMENT: Department heads, managers, auditors
 * - ADMIN: IT administrators, system managers
 */

-- ============================================
-- ASSIGN ADMIN ROLES
-- ============================================
-- Replace with your actual admin email addresses

UPDATE users 
SET role = 'ADMIN'
WHERE email IN (
  'admin@royalenfield.com',
  'it.admin@royalenfield.com',
  'system.admin@royalenfield.com'
  -- Add more admin emails here
);

-- Verify ADMIN users
SELECT 
  email, 
  display_name, 
  role,
  updated_at 
FROM users 
WHERE role = 'ADMIN'
ORDER BY email;

-- ============================================
-- ASSIGN MANAGEMENT ROLES
-- ============================================
-- Replace with your actual management email addresses

UPDATE users 
SET role = 'MANAGEMENT'
WHERE email IN (
  'manager1@royalenfield.com',
  'dept.head@royalenfield.com',
  'auditor@royalenfield.com'
  -- Add more management emails here
);

-- Verify MANAGEMENT users
SELECT 
  email, 
  display_name, 
  department,
  role,
  updated_at 
FROM users 
WHERE role = 'MANAGEMENT'
ORDER BY department, email;

-- ============================================
-- VERIFY ALL ROLES
-- ============================================

SELECT 
  role,
  COUNT(*) as user_count
FROM users 
WHERE is_active = true
GROUP BY role
ORDER BY 
  CASE role
    WHEN 'ADMIN' THEN 1
    WHEN 'MANAGEMENT' THEN 2
    WHEN 'USER' THEN 3
  END;

-- ============================================
-- EXAMPLE: Assign role by department
-- ============================================

-- Make all users in "IT" department as ADMIN
-- UPDATE users 
-- SET role = 'ADMIN'
-- WHERE department = 'IT' AND is_active = true;

-- Make all users in "Management" department as MANAGEMENT
-- UPDATE users 
-- SET role = 'MANAGEMENT'
-- WHERE department = 'Management' AND is_active = true;

-- ============================================
-- EXAMPLE: Assign role by designation
-- ============================================

-- Make all "Department Head" as MANAGEMENT
-- UPDATE users 
-- SET role = 'MANAGEMENT'
-- WHERE (designation ILIKE '%head%' OR designation ILIKE '%manager%') 
-- AND is_active = true;

-- ============================================
-- Display role summary
-- ============================================

\echo '\n✅ Role assignment complete!\n'
\echo 'Role Summary:'
SELECT 
  role,
  COUNT(*) as total_users,
  COUNT(CASE WHEN is_active = true THEN 1 END) as active_users
FROM users 
GROUP BY role
ORDER BY 
  CASE role
    WHEN 'ADMIN' THEN 1
    WHEN 'MANAGEMENT' THEN 2
    WHEN 'USER' THEN 3
  END;
