CREATE TABLE IF NOT EXISTS public.owner_registration_requests (
  id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
  association_id uuid REFERENCES public.associations(id) ON DELETE SET NULL,
  owner_id uuid REFERENCES public.owners(id) ON DELETE SET NULL,
  unit_id uuid REFERENCES public.units(id) ON DELETE SET NULL,
  last_name text NOT NULL,
  email text NOT NULL,
  unit_identifier text NOT NULL,
  account_number text NOT NULL,
  status text NOT NULL DEFAULT 'pending',
  notes text,
  reviewed_by uuid,
  reviewed_at timestamp with time zone,
  created_user_id uuid,
  created_at timestamp with time zone NOT NULL DEFAULT now(),
  updated_at timestamp with time zone NOT NULL DEFAULT now()
);

ALTER TABLE public.owner_registration_requests ENABLE ROW LEVEL SECURITY;

DROP POLICY IF EXISTS "Anyone can submit owner registration requests" ON public.owner_registration_requests;
CREATE POLICY "Anyone can submit owner registration requests"
ON public.owner_registration_requests
FOR INSERT
WITH CHECK (status = 'pending');

DROP POLICY IF EXISTS "Staff can view owner registration requests" ON public.owner_registration_requests;
CREATE POLICY "Staff can view owner registration requests"
ON public.owner_registration_requests
FOR SELECT
USING (public.has_role(auth.uid(), 'admin'::public.app_role) OR public.has_role(auth.uid(), 'manager'::public.app_role));

DROP POLICY IF EXISTS "Staff can update owner registration requests" ON public.owner_registration_requests;
CREATE POLICY "Staff can update owner registration requests"
ON public.owner_registration_requests
FOR UPDATE
USING (public.has_role(auth.uid(), 'admin'::public.app_role) OR public.has_role(auth.uid(), 'manager'::public.app_role));

CREATE INDEX IF NOT EXISTS idx_owner_registration_requests_status ON public.owner_registration_requests(status);
CREATE INDEX IF NOT EXISTS idx_owner_registration_requests_email ON public.owner_registration_requests(lower(email));
CREATE INDEX IF NOT EXISTS idx_owner_registration_requests_owner_id ON public.owner_registration_requests(owner_id);

DROP TRIGGER IF EXISTS update_owner_registration_requests_updated_at ON public.owner_registration_requests;
CREATE TRIGGER update_owner_registration_requests_updated_at
BEFORE UPDATE ON public.owner_registration_requests
FOR EACH ROW
EXECUTE FUNCTION public.update_updated_at_column();