ALTER TABLE public.arc_committee_members
  ADD COLUMN IF NOT EXISTS start_date date,
  ADD COLUMN IF NOT EXISTS end_date date;

CREATE OR REPLACE FUNCTION public.sync_committee_member_active_from_dates()
RETURNS trigger
LANGUAGE plpgsql
SET search_path TO 'public'
AS $$
DECLARE
  today date := (now() AT TIME ZONE 'America/New_York')::date;
BEGIN
  IF (NEW.start_date IS NOT NULL AND NEW.start_date > today)
     OR (NEW.end_date IS NOT NULL AND NEW.end_date < today) THEN
    NEW.is_active := false;
  ELSE
    NEW.is_active := true;
  END IF;
  RETURN NEW;
END;
$$;

DROP TRIGGER IF EXISTS sync_committee_member_active ON public.arc_committee_members;
CREATE TRIGGER sync_committee_member_active
BEFORE INSERT OR UPDATE OF start_date, end_date ON public.arc_committee_members
FOR EACH ROW EXECUTE FUNCTION public.sync_committee_member_active_from_dates();

-- Daily refresh: deactivate expired / activate current term members
CREATE OR REPLACE FUNCTION public.refresh_committee_member_active_status()
RETURNS void
LANGUAGE plpgsql
SECURITY DEFINER
SET search_path TO 'public'
AS $$
DECLARE
  today date := (now() AT TIME ZONE 'America/New_York')::date;
BEGIN
  UPDATE public.arc_committee_members
  SET is_active = false, updated_at = now()
  WHERE is_active = true
    AND ((start_date IS NOT NULL AND start_date > today)
         OR (end_date IS NOT NULL AND end_date < today));

  UPDATE public.arc_committee_members
  SET is_active = true, updated_at = now()
  WHERE is_active = false
    AND (start_date IS NULL OR start_date <= today)
    AND (end_date IS NULL OR end_date >= today);
END;
$$;