-- Fix RLS policies on inquiries table
-- Replace always-true policies with meaningful checks

DROP POLICY IF EXISTS "insert_inquiries" ON inquiries;
DROP POLICY IF EXISTS "update_inquiries" ON inquiries;
DROP POLICY IF EXISTS "delete_inquiries" ON inquiries;

-- INSERT: anon can submit forms, but data must be valid (non-empty required fields, valid email)
CREATE POLICY "insert_inquiries" ON inquiries
  FOR INSERT TO anon, authenticated
  WITH CHECK (
    name IS NOT NULL AND length(btrim(name)) > 0
    AND email IS NOT NULL AND email ~ '^[^@]+@[^@]+\.[^@]+$'
    AND phone IS NOT NULL AND length(btrim(phone)) > 0
    AND location IS NOT NULL AND length(btrim(location)) > 0
    AND project_type IS NOT NULL AND length(btrim(project_type)) > 0
    AND message IS NOT NULL AND length(btrim(message)) > 0
  );

-- UPDATE: only authenticated users (admins), and they must be signed in
CREATE POLICY "update_inquiries" ON inquiries
  FOR UPDATE TO authenticated
  USING (auth.uid() IS NOT NULL)
  WITH CHECK (auth.uid() IS NOT NULL);

-- DELETE: only authenticated users (admins)
CREATE POLICY "delete_inquiries" ON inquiries
  FOR DELETE TO authenticated
  USING (auth.uid() IS NOT NULL);

-- Fix RLS policies on quote_requests table
DROP POLICY IF EXISTS "insert_quote_requests" ON quote_requests;
DROP POLICY IF EXISTS "update_quote_requests" ON quote_requests;
DROP POLICY IF EXISTS "delete_quote_requests" ON quote_requests;

-- INSERT: anon can submit quote requests with valid data
CREATE POLICY "insert_quote_requests" ON quote_requests
  FOR INSERT TO anon, authenticated
  WITH CHECK (
    name IS NOT NULL AND length(btrim(name)) > 0
    AND email IS NOT NULL AND email ~ '^[^@]+@[^@]+\.[^@]+$'
    AND phone IS NOT NULL AND length(btrim(phone)) > 0
    AND location IS NOT NULL AND length(btrim(location)) > 0
    AND property_type IS NOT NULL AND length(btrim(property_type)) > 0
    AND project_description IS NOT NULL AND length(btrim(project_description)) > 0
  );

-- UPDATE: only authenticated users (admins)
CREATE POLICY "update_quote_requests" ON quote_requests
  FOR UPDATE TO authenticated
  USING (auth.uid() IS NOT NULL)
  WITH CHECK (auth.uid() IS NOT NULL);

-- DELETE: only authenticated users (admins)
CREATE POLICY "delete_quote_requests" ON quote_requests
  FOR DELETE TO authenticated
  USING (auth.uid() IS NOT NULL);
