CREATE TABLE IF NOT EXISTS pages (
  id SERIAL PRIMARY KEY,
  page_key VARCHAR(255) NOT NULL UNIQUE,
  page_title VARCHAR(255) NOT NULL,
  content TEXT,
  created_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP,
  updated_at TIMESTAMPTZ DEFAULT CURRENT_TIMESTAMP
);

CREATE OR REPLACE FUNCTION update_updated_at_column()
RETURNS TRIGGER AS $$
BEGIN
    NEW.updated_at = NOW();
    RETURN NEW;
END;
$$ language 'plpgsql';

DO $$
BEGIN
    IF NOT EXISTS (
        SELECT 1
        FROM pg_trigger
        WHERE tgname = 'update_pages_updated_at'
    ) THEN
        CREATE TRIGGER update_pages_updated_at
        BEFORE UPDATE ON pages
        FOR EACH ROW
        EXECUTE FUNCTION update_updated_at_column();
    END IF;
END;
$$;

INSERT INTO pages (page_key, page_title, content) VALUES
('about_us', 'About Us', '<h1>About Us</h1><p>Welcome to our website. This is the about us page. You can edit this content from the admin dashboard.</p>'),
('how_it_works', 'How It Works', '<h1>How It Works</h1><p>This is the how it works page. You can edit this content from the admin dashboard.</p>')
ON CONFLICT (page_key) DO NOTHING;