-- Circle (Close Friends) Privacy Feature
-- Allows users to share posts only with a specific inner circle

CREATE TABLE IF NOT EXISTS public.circle_members (
    user_id UUID NOT NULL REFERENCES public.profiles(id) ON DELETE CASCADE,
    member_id UUID NOT NULL REFERENCES public.profiles(id) ON DELETE CASCADE,
    created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
    PRIMARY KEY (user_id, member_id),
    -- Prevent self-addition
    CHECK (user_id != member_id)
);

-- Index for fast circle membership checks
CREATE INDEX IF NOT EXISTS idx_circle_members_user_id ON public.circle_members(user_id);
CREATE INDEX IF NOT EXISTS idx_circle_members_member_id ON public.circle_members(member_id);

-- Helper function to check if a user is in another user's circle
CREATE OR REPLACE FUNCTION public.is_in_circle(circle_owner_id UUID, potential_member_id UUID)
RETURNS BOOLEAN AS $$
BEGIN
    RETURN EXISTS (
        SELECT 1 FROM public.circle_members
        WHERE user_id = circle_owner_id AND member_id = potential_member_id
    );
END;
$$ LANGUAGE plpgsql SECURITY DEFINER STABLE;
