defmodule Tololo.Repo.Migrations.MigrateResources1 do
  @moduledoc """
  Updates resources based on their most recent snapshots.

  This file was autogenerated with `mix ash_postgres.generate_migrations`
  """

  use Ecto.Migration

  def up do
    create table(:delivery_state_changes, primary_key: false) do
      add :id, :uuid, null: false, default: fragment("uuid_generate_v7()"), primary_key: true
      add :old_state, :text
      add :new_state, :text, null: false
      add :comment, :text

      add :inserted_at, :utc_datetime_usec,
        null: false,
        default: fragment("(now() AT TIME ZONE 'utc')")

      add :updated_at, :utc_datetime_usec,
        null: false,
        default: fragment("(now() AT TIME ZONE 'utc')")

      add :delivery_id, :uuid
    end

    create table(:deliveries, primary_key: false) do
      add :id, :uuid, null: false, default: fragment("uuid_generate_v7()"), primary_key: true
    end

    alter table(:delivery_state_changes) do
      modify :delivery_id,
             references(:deliveries,
               column: :id,
               name: "delivery_state_changes_delivery_id_fkey",
               type: :uuid,
               prefix: "public"
             )
    end

    alter table(:deliveries) do
      add :state, :text, null: false
      add :private_auth_key, :uuid, null: false
      add :public_auth_key, :uuid, null: false
      add :delivery_person, :map
      add :delivery_order, :map
      add :from_latitude, :float
      add :from_longitude, :float
      add :from_name, :text
      add :to_latitude, :float
      add :to_longitude, :float
      add :to_name, :text
      add :to_address, :text
      add :to_phone, :text
      add :to_notes, :text
      add :delivery_started_at, :date
      add :delivery_ended_at, :date

      add :inserted_at, :utc_datetime_usec,
        null: false,
        default: fragment("(now() AT TIME ZONE 'utc')")

      add :updated_at, :utc_datetime_usec,
        null: false,
        default: fragment("(now() AT TIME ZONE 'utc')")
    end
  end

  def down do
    alter table(:deliveries) do
      remove :updated_at
      remove :inserted_at
      remove :delivery_ended_at
      remove :delivery_started_at
      remove :to_notes
      remove :to_phone
      remove :to_address
      remove :to_name
      remove :to_longitude
      remove :to_latitude
      remove :from_name
      remove :from_longitude
      remove :from_latitude
      remove :delivery_order
      remove :delivery_person
      remove :public_auth_key
      remove :private_auth_key
      remove :state
    end

    drop constraint(:delivery_state_changes, "delivery_state_changes_delivery_id_fkey")

    alter table(:delivery_state_changes) do
      modify :delivery_id, :uuid
    end

    drop table(:deliveries)

    drop table(:delivery_state_changes)
  end
end
