-- Update existing user_club entries with default permissions
-- This migration sets default values for role and is_owner for existing club memberships

-- Set default role to 'member' for all approved users who don't have a role yet
UPDATE `user_club` 
SET `role` = 'member' 
WHERE `approved` = 1 
  AND (`role` IS NULL OR `role` = '');

-- Optionally: Set the first approved user of each club as owner
-- This finds the user with the lowest user_id per club (oldest member) and marks them as owner
UPDATE `user_club` AS uc1
INNER JOIN (
    SELECT `club_id`, MIN(`user_id`) as `first_user_id`
    FROM `user_club`
    WHERE `approved` = 1
    GROUP BY `club_id`
) AS uc2 ON uc1.`club_id` = uc2.`club_id` AND uc1.`user_id` = uc2.`first_user_id`
SET 
    uc1.`is_owner` = 1,
    uc1.`role` = 'admin';

-- Verify the changes
SELECT 
    uc.`club_id`,
    c.`name` as club_name,
    uc.`user_id`,
    u.`email` as user_email,
    uc.`role`,
    uc.`is_owner`,
    uc.`approved`
FROM `user_club` uc
LEFT JOIN `club` c ON c.`id` = uc.`club_id`
LEFT JOIN `user` u ON u.`id` = uc.`user_id`
WHERE uc.`approved` = 1
ORDER BY uc.`club_id`, uc.`is_owner` DESC, uc.`user_id`;


