-- Create super admin user for platform administration

USE freedb_test45;

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

-- 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 'Super Admin Permissions' as status;

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