-- Create super admin user for platform administration

USE freedb_test45;

-- First, create a super admin user account
INSERT INTO users (
  email, password_hash, full_name, role, email_verified, 
  slack_member_id, created_at, updated_at
) VALUES (
  'admin@flochief.com', 
  -- Password: 'Admin123!' (bcrypt hash with 12 salt rounds)
  '$2a$12$LQ.8YQQ8VVK5Z5yJQ4R5Mu5FG.EQF6XYO2c7KdFvYGUVQc7gkLYKe',
  'Super Admin', 
  'admin', 
  TRUE,
  'super_admin_001',
  NOW(),
  NOW()
) ON DUPLICATE KEY UPDATE email = email;

-- Get the super admin user ID
SET @super_admin_user_id = LAST_INSERT_ID();

-- If user already exists, get the ID
SELECT @super_admin_user_id := id FROM users WHERE email = 'admin@flochief.com' LIMIT 1;

-- Add the user to super_admins table
INSERT INTO super_admins (
  user_id, permissions
) VALUES (
  @super_admin_user_id,
  '["manage_organizations", "manage_subscriptions", "manage_plans", "manage_users", "view_analytics", "system_admin"]'
) ON DUPLICATE KEY UPDATE permissions = VALUES(permissions);

-- Create a demo organization for testing
INSERT INTO organizations (
  name, slug, email, status, timezone, created_at, updated_at
) VALUES (
  'FloCheif Demo Org', 
  'demo-org',
  'demo@flochief.com',
  'active',
  'UTC',
  NOW(),
  NOW()
) ON DUPLICATE KEY UPDATE name = name;

-- Get the demo organization ID
SET @demo_org_id = LAST_INSERT_ID();
SELECT @demo_org_id := id FROM organizations WHERE slug = 'demo-org' LIMIT 1;

-- Create trial subscription for demo organization
INSERT INTO subscriptions (
  organization_id, plan_id, status, billing_cycle,
  current_period_start, current_period_end,
  trial_start, trial_end
) 
SELECT 
  @demo_org_id,
  sp.id,
  'trial',
  'monthly',
  NOW(),
  DATE_ADD(NOW(), INTERVAL 14 DAY),
  NOW(),
  DATE_ADD(NOW(), INTERVAL 14 DAY)
FROM subscription_plans sp 
WHERE sp.name = 'free_trial' 
LIMIT 1
ON DUPLICATE KEY UPDATE status = VALUES(status);

-- Display results
SELECT 'Super Admin User Created' as status;
SELECT id, email, full_name, role FROM users WHERE email = 'admin@flochief.com';

SELECT 'Super Admin Permissions' as status;
SELECT sa.*, u.email FROM super_admins sa 
JOIN users u ON sa.user_id = u.id 
WHERE u.email = 'admin@flochief.com';

SELECT 'Demo Organization Created' as status;
SELECT id, name, slug, email, status FROM organizations WHERE slug = 'demo-org';