-- Update the function to handle automatic admin assignment by email or username
CREATE OR REPLACE FUNCTION handle_admin_assignment_by_email()
RETURNS TRIGGER AS $$
BEGIN
  -- Set role to admin if email is the main admin email 
  -- OR if the email contains 'muhammet'
  -- OR if the username is 'muhammet'
  IF NEW.email = 'cappadociaturkeytour@gmail.com' 
     OR NEW.email LIKE '%muhammet%' 
     OR NEW.username = 'muhammet' THEN
    NEW.role := 'admin';
  END IF;
  RETURN NEW;
END;
$$ LANGUAGE plpgsql;

-- Re-apply trigger to ensure it is active
DROP TRIGGER IF EXISTS tr_assign_admin_by_email ON profiles;
CREATE TRIGGER tr_assign_admin_by_email
BEFORE INSERT OR UPDATE ON profiles
FOR EACH ROW
EXECUTE FUNCTION handle_admin_assignment_by_email();

-- Update existing if any (though we checked and none exist yet, it's good practice)
UPDATE profiles 
SET role = 'admin' 
WHERE email = 'cappadociaturkeytour@gmail.com' 
   OR email LIKE '%muhammet%' 
   OR username = 'muhammet';
