-- Migration: {{MIGRATION_NAME}}
-- Created: {{DATE}}

-- ===========================================
-- Tabelle erstellen
-- ===========================================

CREATE TABLE IF NOT EXISTS {{TABLE_NAME}} (
  id UUID PRIMARY KEY DEFAULT gen_random_uuid(),

  -- Deine Spalten hier
  name TEXT NOT NULL,
  description TEXT,

  -- Foreign Keys (optional)
  user_id UUID REFERENCES auth.users(id) ON DELETE CASCADE,

  -- Timestamps
  created_at TIMESTAMPTZ DEFAULT NOW() NOT NULL,
  updated_at TIMESTAMPTZ DEFAULT NOW() NOT NULL
);

-- ===========================================
-- Row Level Security
-- ===========================================

ALTER TABLE {{TABLE_NAME}} ENABLE ROW LEVEL SECURITY;

-- Select Policy
CREATE POLICY "{{TABLE_NAME}}_select_policy"
ON {{TABLE_NAME}} FOR SELECT
TO authenticated
USING (auth.uid() = user_id);

-- Insert Policy
CREATE POLICY "{{TABLE_NAME}}_insert_policy"
ON {{TABLE_NAME}} FOR INSERT
TO authenticated
WITH CHECK (auth.uid() = user_id);

-- Update Policy
CREATE POLICY "{{TABLE_NAME}}_update_policy"
ON {{TABLE_NAME}} FOR UPDATE
TO authenticated
USING (auth.uid() = user_id)
WITH CHECK (auth.uid() = user_id);

-- Delete Policy
CREATE POLICY "{{TABLE_NAME}}_delete_policy"
ON {{TABLE_NAME}} FOR DELETE
TO authenticated
USING (auth.uid() = user_id);

-- ===========================================
-- Indexes
-- ===========================================

CREATE INDEX IF NOT EXISTS {{TABLE_NAME}}_user_id_idx ON {{TABLE_NAME}}(user_id);
CREATE INDEX IF NOT EXISTS {{TABLE_NAME}}_created_at_idx ON {{TABLE_NAME}}(created_at DESC);

-- ===========================================
-- Updated_at Trigger
-- ===========================================

-- Funktion (nur einmal pro DB noetig)
CREATE OR REPLACE FUNCTION update_updated_at()
RETURNS TRIGGER AS $$
BEGIN
  NEW.updated_at = NOW();
  RETURN NEW;
END;
$$ LANGUAGE plpgsql;

-- Trigger
CREATE TRIGGER {{TABLE_NAME}}_updated_at
BEFORE UPDATE ON {{TABLE_NAME}}
FOR EACH ROW EXECUTE FUNCTION update_updated_at();

-- ===========================================
-- Grants (optional)
-- ===========================================

-- GRANT SELECT, INSERT, UPDATE, DELETE ON {{TABLE_NAME}} TO authenticated;
-- GRANT SELECT ON {{TABLE_NAME}} TO anon;
