const { query } = require('./db')

async function runMigrations() {
  await query(`
    CREATE TABLE IF NOT EXISTS blog_posts (
      id SERIAL PRIMARY KEY,
      title TEXT NOT NULL,
      slug TEXT NOT NULL UNIQUE,
      preview_image TEXT,
      link_url TEXT,
      sections JSONB NOT NULL DEFAULT '[]'::jsonb,
      footer TEXT,
      is_editors_pick BOOLEAN NOT NULL DEFAULT FALSE,
      category TEXT,
      created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
      updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
    );
  `)

  await query(`
    DO $$
    BEGIN
      IF NOT EXISTS (
        SELECT 1
        FROM information_schema.columns
        WHERE table_name = 'blog_posts'
        AND column_name = 'category'
      ) THEN
        ALTER TABLE blog_posts ADD COLUMN category TEXT;
      END IF;
    END $$;
  `)

  await query(`
    CREATE OR REPLACE FUNCTION set_updated_at()
    RETURNS TRIGGER AS $$
    BEGIN
      NEW.updated_at = NOW();
      RETURN NEW;
    END;
    $$ LANGUAGE plpgsql;
  `)

  await query(`
    DO $$
    BEGIN
      IF NOT EXISTS (
        SELECT 1
        FROM pg_trigger
        WHERE tgname = 'trg_blog_posts_updated_at'
      ) THEN
        CREATE TRIGGER trg_blog_posts_updated_at
        BEFORE UPDATE ON blog_posts
        FOR EACH ROW
        EXECUTE PROCEDURE set_updated_at();
      END IF;
    END; $$;
  `)
}

module.exports = { runMigrations }
