
-- Create autopay enrollments table
CREATE TABLE public.autopay_enrollments (
  id UUID NOT NULL DEFAULT gen_random_uuid() PRIMARY KEY,
  association_id UUID NOT NULL REFERENCES public.associations(id) ON DELETE CASCADE,
  owner_id UUID REFERENCES public.owners(id) ON DELETE SET NULL,
  unit_id UUID REFERENCES public.units(id) ON DELETE SET NULL,
  stripe_customer_id TEXT NOT NULL,
  stripe_payment_method_id TEXT NOT NULL,
  payment_method_type TEXT NOT NULL DEFAULT 'card',
  is_active BOOLEAN NOT NULL DEFAULT true,
  enrolled_by UUID,
  created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(),
  updated_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now()
);

-- Enable RLS
ALTER TABLE public.autopay_enrollments ENABLE ROW LEVEL SECURITY;

-- Admin/manager full access
CREATE POLICY "Admins can manage all autopay enrollments"
ON public.autopay_enrollments
FOR ALL
TO authenticated
USING (
  public.has_role(auth.uid(), 'admin') OR public.has_role(auth.uid(), 'manager')
)
WITH CHECK (
  public.has_role(auth.uid(), 'admin') OR public.has_role(auth.uid(), 'manager')
);

-- Owners can view their own
CREATE POLICY "Users can view own autopay enrollments"
ON public.autopay_enrollments
FOR SELECT
TO authenticated
USING (enrolled_by = auth.uid());

-- Owners can create their own
CREATE POLICY "Users can create own autopay enrollments"
ON public.autopay_enrollments
FOR INSERT
TO authenticated
WITH CHECK (enrolled_by = auth.uid());

-- Owners can update their own
CREATE POLICY "Users can update own autopay enrollments"
ON public.autopay_enrollments
FOR UPDATE
TO authenticated
USING (enrolled_by = auth.uid());

-- Timestamp trigger
CREATE TRIGGER update_autopay_enrollments_updated_at
BEFORE UPDATE ON public.autopay_enrollments
FOR EACH ROW
EXECUTE FUNCTION public.update_updated_at_column();
