-- Create unit_documents table for per-unit document storage
CREATE TABLE public.unit_documents (
  id UUID NOT NULL DEFAULT gen_random_uuid() PRIMARY KEY,
  unit_id UUID NOT NULL REFERENCES public.units(id) ON DELETE CASCADE,
  association_id UUID NOT NULL REFERENCES public.associations(id) ON DELETE CASCADE,
  title TEXT NOT NULL,
  file_name TEXT,
  file_url TEXT,
  file_size BIGINT,
  category TEXT DEFAULT 'general',
  uploaded_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.unit_documents ENABLE ROW LEVEL SECURITY;

-- Admin/manager can do everything
CREATE POLICY "Staff can manage unit documents"
ON public.unit_documents
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')
);

-- Legal, board_member can view unit documents (read-only)
CREATE POLICY "Legal and board members can view unit documents"
ON public.unit_documents
FOR SELECT
TO authenticated
USING (
  public.has_role(auth.uid(), 'legal') OR public.has_role(auth.uid(), 'board_member')
);

-- Add RLS policy for legal role to read legal_matters
CREATE POLICY "Legal users can view legal matters"
ON public.legal_matters
FOR SELECT
TO authenticated
USING (
  public.has_role(auth.uid(), 'legal')
);

-- Add RLS policies for legal role to read owner/unit data
CREATE POLICY "Legal users can view units"
ON public.units
FOR SELECT
TO authenticated
USING (
  public.has_role(auth.uid(), 'legal')
);

CREATE POLICY "Legal users can view owners"
ON public.owners
FOR SELECT
TO authenticated
USING (
  public.has_role(auth.uid(), 'legal')
);

CREATE POLICY "Legal users can view associations"
ON public.associations
FOR SELECT
TO authenticated
USING (
  public.has_role(auth.uid(), 'legal')
);

CREATE POLICY "Legal users can view owner ledger entries"
ON public.owner_ledger_entries
FOR SELECT
TO authenticated
USING (
  public.has_role(auth.uid(), 'legal')
);

-- Add indexes
CREATE INDEX idx_unit_documents_unit_id ON public.unit_documents(unit_id);
CREATE INDEX idx_unit_documents_association_id ON public.unit_documents(association_id);

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