-- Add profile_completion_percentage column
ALTER TABLE users ADD COLUMN profile_completion_percentage SMALLINT NOT NULL DEFAULT 0;

-- Create function to calculate profile completion
CREATE OR REPLACE FUNCTION calculate_profile_completion()
RETURNS TRIGGER AS $$
DECLARE
    filled_count INTEGER := 0;
BEGIN
    -- Check first_name
    IF NULLIF(TRIM(NEW.first_name), '') IS NOT NULL THEN
        filled_count := filled_count + 1;
    END IF;

    -- Check last_name
    IF NULLIF(TRIM(NEW.last_name), '') IS NOT NULL THEN
        filled_count := filled_count + 1;
    END IF;

    -- Check email OR phone_number (counts as 1 if either is filled)
    IF NULLIF(TRIM(NEW.email), '') IS NOT NULL OR NULLIF(TRIM(NEW.phone_number), '') IS NOT NULL THEN
        filled_count := filled_count + 1;
    END IF;

    -- Check preferred_language
    IF NULLIF(TRIM(NEW.preferred_language), '') IS NOT NULL THEN
        filled_count := filled_count + 1;
    END IF;

    -- Check country
    IF NULLIF(TRIM(NEW.country), '') IS NOT NULL THEN
        filled_count := filled_count + 1;
    END IF;

    -- Check age_group
    IF NULLIF(TRIM(NEW.age_group), '') IS NOT NULL THEN
        filled_count := filled_count + 1;
    END IF;

    -- Check knowledge_level
    IF NULLIF(TRIM(NEW.knowledge_level), '') IS NOT NULL THEN
        filled_count := filled_count + 1;
    END IF;

    -- Check learning_goal
    IF NULLIF(TRIM(NEW.learning_goal), '') IS NOT NULL THEN
        filled_count := filled_count + 1;
    END IF;

    -- Check language_goal
    IF NULLIF(TRIM(NEW.language_goal), '') IS NOT NULL THEN
        filled_count := filled_count + 1;
    END IF;

    -- Calculate percentage (9 total required fields)
    NEW.profile_completion_percentage := (filled_count * 100 / 9)::SMALLINT;

    -- Set profile_completed if 100%
    IF NEW.profile_completion_percentage = 100 THEN
        NEW.profile_completed := true;
    ELSE
        NEW.profile_completed := false;
    END IF;

    RETURN NEW;
END;
$$ LANGUAGE plpgsql;

-- Create trigger
CREATE TRIGGER trg_update_profile_completion
    BEFORE INSERT OR UPDATE ON users
    FOR EACH ROW
    EXECUTE FUNCTION calculate_profile_completion();

-- Backfill existing rows
UPDATE users SET updated_at = updated_at;
