ALTER TABLE guilds
    ADD FOREIGN KEY (owner_id) REFERENCES users(id) ON DELETE CASCADE,
    ADD FOREIGN KEY (afk_channel_id) REFERENCES channels(id) ON DELETE SET NULL,
    ADD FOREIGN KEY (system_channel_id) REFERENCES channels(id) ON DELETE SET NULL,
    ADD FOREIGN KEY (widget_channel_id) REFERENCES channels(id) ON DELETE SET NULL;

-- For "my guilds" query
CREATE INDEX idx_guild_members_guild_id_user_id ON guild_members (guild_id, user_id);

-- Ensure member_count is updated on membership changes
CREATE OR REPLACE FUNCTION update_guild_member_counts()
    RETURNS TRIGGER AS $$
DECLARE
    new_count INTEGER;
BEGIN
    IF TG_OP = 'INSERT' THEN
        new_count := (SELECT COUNT(*) FROM guild_members WHERE guild_id = NEW.guild_id);
        UPDATE guilds SET member_count = new_count, large = (new_count > 150) WHERE id = NEW.guild_id;
        RETURN NEW;
    ELSIF TG_OP = 'DELETE' THEN
        new_count := (SELECT COUNT(*) FROM guild_members WHERE guild_id = OLD.guild_id);
        UPDATE guilds SET member_count = new_count, large = (new_count > 150) WHERE id = OLD.guild_id;
        RETURN OLD;
    END IF;
    RETURN NULL;
END;
$$ LANGUAGE plpgsql;

CREATE TRIGGER update_guild_counts_on_member_change
    AFTER INSERT OR DELETE ON guild_members
    FOR EACH ROW
EXECUTE FUNCTION update_guild_member_counts();