-- ============================================================
-- Migration: native_articles
-- Timestamp: 20260321070000
-- ============================================================

-- 1. native_articles table
CREATE TABLE IF NOT EXISTS public.native_articles (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
  slug TEXT NOT NULL,
  title TEXT NOT NULL,
  excerpt TEXT,
  content TEXT,
  author_name TEXT,
  author_id UUID REFERENCES public.user_profiles(id) ON DELETE SET NULL,
  category TEXT,
  tags TEXT[],
  featured_image TEXT,
  featured_image_alt TEXT,
  status TEXT NOT NULL DEFAULT 'draft',
  published_at TIMESTAMPTZ,
  created_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP,
  updated_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP
);

CREATE UNIQUE INDEX IF NOT EXISTS idx_native_articles_slug ON public.native_articles(slug);
CREATE INDEX IF NOT EXISTS idx_native_articles_status ON public.native_articles(status);
CREATE INDEX IF NOT EXISTS idx_native_articles_created_at ON public.native_articles(created_at DESC);
CREATE INDEX IF NOT EXISTS idx_native_articles_author_id ON public.native_articles(author_id);

-- 2. Enable RLS
ALTER TABLE public.native_articles ENABLE ROW LEVEL SECURITY;

-- 3. RLS Policies
DROP POLICY IF EXISTS "public_read_published_native_articles" ON public.native_articles;
CREATE POLICY "public_read_published_native_articles"
ON public.native_articles
FOR SELECT
TO public
USING (status = 'published');

DROP POLICY IF EXISTS "authenticated_manage_native_articles" ON public.native_articles;
CREATE POLICY "authenticated_manage_native_articles"
ON public.native_articles
FOR ALL
TO authenticated
USING (true)
WITH CHECK (true);

-- 4. Trigger for updated_at
DROP TRIGGER IF EXISTS update_native_articles_updated_at ON public.native_articles;
CREATE TRIGGER update_native_articles_updated_at
  BEFORE UPDATE ON public.native_articles
  FOR EACH ROW EXECUTE FUNCTION public.update_updated_at();
