-- Migration 003: Create contracts storage bucket + reservation_contracts table
-- Schema: natur_reservas
-- Run in Supabase SQL editor

-- ── 1. Storage bucket (privado, usa signed URLs) ──────────────────────────────
INSERT INTO storage.buckets (id, name, public, file_size_limit, allowed_mime_types)
VALUES (
  'contracts',
  'contracts',
  false,
  10485760,
  ARRAY['application/pdf', 'image/jpeg', 'image/png']
)
ON CONFLICT (id) DO NOTHING;

-- Storage RLS policies
CREATE POLICY "contracts: select"
  ON storage.objects FOR SELECT TO anon, authenticated
  USING (bucket_id = 'contracts');

CREATE POLICY "contracts: insert"
  ON storage.objects FOR INSERT TO anon, authenticated
  WITH CHECK (bucket_id = 'contracts');

CREATE POLICY "contracts: update"
  ON storage.objects FOR UPDATE TO anon, authenticated
  USING (bucket_id = 'contracts');

CREATE POLICY "contracts: delete"
  ON storage.objects FOR DELETE TO anon, authenticated
  USING (bucket_id = 'contracts');

-- ── 2. Tabla reservation_contracts ────────────────────────────────────────────
CREATE TABLE IF NOT EXISTS natur_reservas.reservation_contracts (
  id          uuid    DEFAULT gen_random_uuid() PRIMARY KEY,
  created_at  timestamp with time zone DEFAULT timezone('utc', now()) NOT NULL,
  reservation_id uuid NOT NULL REFERENCES natur_reservas.reservations(id) ON DELETE CASCADE,
  file_path   text    NOT NULL,
  filename    text    NOT NULL,
  mime_type   text    NOT NULL,
  size_bytes  integer NOT NULL,
  uploaded_by uuid    REFERENCES auth.users(id)
);

ALTER TABLE natur_reservas.reservation_contracts ENABLE ROW LEVEL SECURITY;

CREATE POLICY "rc: select" ON natur_reservas.reservation_contracts
  FOR SELECT TO anon, authenticated USING (true);

CREATE POLICY "rc: insert" ON natur_reservas.reservation_contracts
  FOR INSERT TO anon, authenticated WITH CHECK (true);

CREATE POLICY "rc: delete" ON natur_reservas.reservation_contracts
  FOR DELETE TO anon, authenticated USING (true);
