
-- Table to store shared links for folders and documents
CREATE TABLE public.shared_links (
  id UUID NOT NULL DEFAULT gen_random_uuid() PRIMARY KEY,
  share_type TEXT NOT NULL DEFAULT 'folder', -- 'folder' or 'document'
  folder_name TEXT, -- for folder shares
  document_id UUID REFERENCES public.documents(id) ON DELETE CASCADE, -- for document shares
  is_public BOOLEAN NOT NULL DEFAULT false,
  access_code TEXT NOT NULL,
  share_token TEXT NOT NULL UNIQUE DEFAULT encode(gen_random_bytes(16), 'hex'),
  created_by UUID REFERENCES auth.users(id) ON DELETE SET NULL,
  created_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(),
  updated_at TIMESTAMP WITH TIME ZONE NOT NULL DEFAULT now(),
  expires_at TIMESTAMP WITH TIME ZONE -- optional expiry
);

ALTER TABLE public.shared_links ENABLE ROW LEVEL SECURITY;

-- Staff can manage shared links
CREATE POLICY "Staff full access on shared_links"
ON public.shared_links
FOR ALL
TO authenticated
USING (has_role(auth.uid(), 'admin'::app_role) OR has_role(auth.uid(), 'manager'::app_role))
WITH CHECK (has_role(auth.uid(), 'admin'::app_role) OR has_role(auth.uid(), 'manager'::app_role));

-- Public read for validating access codes (anon users need this)
CREATE POLICY "Anyone can validate shared links"
ON public.shared_links
FOR SELECT
TO anon
USING (is_public = true);

-- Also allow authenticated users to read
CREATE POLICY "Authenticated can read shared links"
ON public.shared_links
FOR SELECT
TO authenticated
USING (true);

-- Trigger for updated_at
CREATE TRIGGER update_shared_links_updated_at
BEFORE UPDATE ON public.shared_links
FOR EACH ROW
EXECUTE FUNCTION public.update_updated_at_column();
