-- 1. Eski politikaları temizle
DROP POLICY IF EXISTS "Allow anonymous trip viewing" ON trips;
DROP POLICY IF EXISTS "Allow anonymous trip update" ON trips;
DROP POLICY IF EXISTS "Allow anonymous trip delete" ON trips;
DROP POLICY IF EXISTS "Allow anonymous trip insert" ON trips;
DROP POLICY IF EXISTS "Secure trip viewing" ON trips;
DROP POLICY IF EXISTS "Secure trip update" ON trips;
DROP POLICY IF EXISTS "Secure trip delete" ON trips;
DROP POLICY IF EXISTS "Secure trip creation" ON trips;

-- 2. Yeni GÜVENLİ politikaları ekle
-- Sadece sahibi veya doğru token'ı olan görebilir (veya is_public ise)
CREATE POLICY "Secure trip viewing" ON trips
    FOR SELECT
    USING (
        (is_public = true) OR 
        (user_id = auth.uid()) OR 
        (
            (user_id IS NULL) AND 
            (anonymous_token IS NOT NULL) AND 
            (anonymous_token = COALESCE((current_setting('request.headers', true)::json->>'x-trip-token'), 'no-token'))
        )
    );

-- Sadece sahibi veya doğru token'ı olan güncelleyebilir
CREATE POLICY "Secure trip update" ON trips
    FOR UPDATE
    USING (
        (user_id = auth.uid()) OR 
        (
            (user_id IS NULL) AND 
            (anonymous_token IS NOT NULL) AND 
            (anonymous_token = COALESCE((current_setting('request.headers', true)::json->>'x-trip-token'), 'no-token'))
        )
    )
    WITH CHECK (
        (user_id = auth.uid()) OR 
        (user_id IS NULL) -- user_id'nin NULL kalmasına veya atanmasına izin ver
    );

-- Sadece sahibi veya doğru token'ı olan silebilir
CREATE POLICY "Secure trip delete" ON trips
    FOR DELETE
    USING (
        (user_id = auth.uid()) OR 
        (
            (user_id IS NULL) AND 
            (anonymous_token IS NOT NULL) AND 
            (anonymous_token = COALESCE((current_setting('request.headers', true)::json->>'x-trip-token'), 'no-token'))
        )
    );

-- Herkes ekleyebilir (auth olsun olmasın) ama anonymous_token üretilmesi frontend'e bağlı
CREATE POLICY "Secure trip creation" ON trips
    FOR INSERT
    WITH CHECK (
        (user_id = auth.uid()) OR 
        (user_id IS NULL)
    );

-- 3. Temizlik fonksiyonu
CREATE OR REPLACE FUNCTION cleanup_anonymous_trips()
RETURNS void AS $$
BEGIN
    -- 7 günden eski ve hâlâ anonim (user_id IS NULL) olan gezileri sil
    DELETE FROM trips
    WHERE user_id IS NULL
    AND created_at < NOW() - INTERVAL '7 days';
END;
$$ LANGUAGE plpgsql SECURITY DEFINER;

-- 4. Cron Job (Eğer pg_cron yüklüyse)
-- Not: Her gece 00:00'da temizle
SELECT cron.schedule('0 0 * * *', 'SELECT cleanup_anonymous_trips()');
