-- Migration: Add UNIQUE constraints to prevent duplicate membership applications and fees
-- Date: 2025-12-05
-- Purpose: Ensure each user can only have one application and one membership fee record
-- Note: Individual payments are tracked in the payments/efts table, not here

-- Add UNIQUE constraint to membership_application table
-- First, delete any duplicate applications keeping the most recent one
DELETE FROM membership_application
WHERE application_id NOT IN (
    SELECT MAX(application_id) 
    FROM (
        SELECT application_id 
        FROM membership_application
    ) tmp
    GROUP BY user_id
);

-- Add UNIQUE constraint on user_id in membership_application
ALTER TABLE membership_application 
ADD CONSTRAINT uk_membership_application_user_id UNIQUE (user_id);

-- Add UNIQUE constraint to membership_fees table
-- First, delete any duplicate fees keeping the most recent one
DELETE FROM membership_fees
WHERE fee_id NOT IN (
    SELECT MAX(fee_id) 
    FROM (
        SELECT fee_id 
        FROM membership_fees
    ) tmp
    GROUP BY user_id
);

-- Add UNIQUE constraint on user_id in membership_fees
ALTER TABLE membership_fees 
ADD CONSTRAINT uk_membership_fees_user_id UNIQUE (user_id);

