-- Migration: Add member_number field to group_members table
-- Date: November 6, 2025
-- Purpose: Add readable serial number for each member within a group

-- Step 1: Add the column (allows NULL temporarily for existing data)
ALTER TABLE group_members 
ADD COLUMN member_number INTEGER;

-- Step 2: Populate member_number for existing members
-- This assigns sequential numbers based on joined_date (earliest = #1)
WITH numbered_members AS (
  SELECT 
    id,
    ROW_NUMBER() OVER (
      PARTITION BY group_id 
      ORDER BY joined_date ASC, created_at ASC
    ) as assigned_number
  FROM group_members
)
UPDATE group_members gm
SET member_number = nm.assigned_number
FROM numbered_members nm
WHERE gm.id = nm.id;

-- Step 3: Make the column NOT NULL
ALTER TABLE group_members 
ALTER COLUMN member_number SET NOT NULL;

-- Step 4: Add unique constraint (group_id + member_number must be unique)
CREATE UNIQUE INDEX idx_group_members_member_number 
ON group_members(group_id, member_number);

-- Step 5: Add comment
COMMENT ON COLUMN group_members.member_number IS 'Readable serial number for the member within this group (1, 2, 3...)';

