-- Migration: Create Donations Table
-- Description: Adds donations table to track both member and public donations
-- Date: 2025-12-17
-- CRITICAL: Fixes data loss issue where standalone donations weren't being saved

BEGIN;

-- Create donation type enum
CREATE TYPE donationtype AS ENUM ('member', 'public');

-- Create donation status enum
CREATE TYPE donationstatus AS ENUM ('pending', 'completed', 'failed');

-- Create donations table
CREATE TABLE donations (
    id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
    amount_cents INTEGER NOT NULL,
    donation_type donationtype NOT NULL DEFAULT 'public',
    status donationstatus NOT NULL DEFAULT 'pending',
    user_id UUID REFERENCES users(id),
    donor_email VARCHAR,
    donor_name VARCHAR,
    stripe_checkout_session_id VARCHAR,
    stripe_payment_intent_id VARCHAR,
    payment_method VARCHAR,
    notes TEXT,
    created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
    updated_at TIMESTAMP WITH TIME ZONE
);

-- Create indexes for performance
CREATE INDEX idx_donation_user ON donations(user_id);
CREATE INDEX idx_donation_type ON donations(donation_type);
CREATE INDEX idx_donation_status ON donations(status);
CREATE INDEX idx_donation_created ON donations(created_at);

-- Add comment
COMMENT ON TABLE donations IS 'Tracks both member and public one-time donations';

COMMIT;

-- Verify migration
SELECT 'Donations table created successfully' as status;
SELECT COUNT(*) as initial_count FROM donations;
