CREATE TABLE IF NOT EXISTS public.legal_association_assignments (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  user_id UUID NOT NULL,
  association_id UUID NOT NULL REFERENCES public.associations(id) ON DELETE CASCADE,
  created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(),
  created_by UUID,
  UNIQUE (user_id, association_id)
);

ALTER TABLE public.legal_association_assignments ENABLE ROW LEVEL SECURITY;

DROP POLICY IF EXISTS "Admins and managers can manage legal assignments" ON public.legal_association_assignments;
DROP POLICY IF EXISTS "Legal users can view their community assignments" ON public.legal_association_assignments;

CREATE POLICY "Admins and managers can manage legal assignments"
ON public.legal_association_assignments
FOR ALL
TO authenticated
USING (
  public.has_role(auth.uid(), 'admin'::public.app_role)
  OR public.has_role(auth.uid(), 'manager'::public.app_role)
)
WITH CHECK (
  public.has_role(auth.uid(), 'admin'::public.app_role)
  OR public.has_role(auth.uid(), 'manager'::public.app_role)
);

CREATE POLICY "Legal users can view their community assignments"
ON public.legal_association_assignments
FOR SELECT
TO authenticated
USING (auth.uid() = user_id);

CREATE INDEX IF NOT EXISTS idx_legal_association_assignments_user_id
ON public.legal_association_assignments(user_id);

CREATE INDEX IF NOT EXISTS idx_legal_association_assignments_association_id
ON public.legal_association_assignments(association_id);

CREATE OR REPLACE FUNCTION public.get_legal_association_ids(_user_id UUID DEFAULT auth.uid())
RETURNS SETOF UUID
LANGUAGE sql
STABLE SECURITY DEFINER
SET search_path TO 'public'
AS $$
  SELECT laa.association_id
  FROM public.legal_association_assignments laa
  WHERE laa.user_id = _user_id
$$;

CREATE OR REPLACE FUNCTION public.legal_user_assigned_to_association(_user_id UUID, _association_id UUID)
RETURNS BOOLEAN
LANGUAGE sql
STABLE SECURITY DEFINER
SET search_path TO 'public'
AS $$
  SELECT EXISTS (
    SELECT 1
    FROM public.legal_association_assignments laa
    WHERE laa.user_id = _user_id
      AND laa.association_id = _association_id
  )
$$;