defmodule Berrypod.Repo.Migrations.AllowNullSocialLinkUrl do
  use Ecto.Migration

  def change do
    # Allow blank URLs so users can add a link and then paste the URL
    # SQLite doesn't support ALTER COLUMN, so we recreate the table
    execute(
      "CREATE TABLE social_links_new (
        id BLOB PRIMARY KEY,
        platform TEXT NOT NULL,
        url TEXT,
        position INTEGER NOT NULL DEFAULT 0,
        inserted_at TEXT NOT NULL,
        updated_at TEXT NOT NULL
      )",
      "DROP TABLE social_links_new"
    )

    execute(
      "INSERT INTO social_links_new SELECT * FROM social_links",
      "INSERT INTO social_links SELECT * FROM social_links_new"
    )

    execute(
      "DROP TABLE social_links",
      "CREATE TABLE social_links (
        id BLOB PRIMARY KEY,
        platform TEXT NOT NULL,
        url TEXT NOT NULL,
        position INTEGER NOT NULL DEFAULT 0,
        inserted_at TEXT NOT NULL,
        updated_at TEXT NOT NULL
      )"
    )

    execute(
      "ALTER TABLE social_links_new RENAME TO social_links",
      "ALTER TABLE social_links RENAME TO social_links_new"
    )

    create index(:social_links, [:position])
  end
end
