defmodule Tololo.Repo.Migrations.Carts 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(:carts, primary_key: false) do
      add :id, :uuid, null: false, default: fragment("uuid_generate_v7()"), primary_key: true
      add :status, :text, default: "active"
      add :currency, :text, default: "CLP"

      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

    create table(:cart_lines, primary_key: false) do
      add :id, :uuid, null: false, default: fragment("uuid_generate_v7()"), primary_key: true
      add :quantity, :bigint, null: false
      add :notes, :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 :variant_id,
          references(:variants,
            column: :id,
            name: "cart_lines_variant_id_fkey",
            type: :uuid,
            prefix: "public"
          ),
          null: false

      add :cart_id,
          references(:carts,
            column: :id,
            name: "cart_lines_cart_id_fkey",
            type: :uuid,
            prefix: "public"
          ),
          null: false
    end

    create unique_index(:cart_lines, [:variant_id, :cart_id],
             name: "cart_lines_unique_variant_index"
           )
  end

  def down do
    drop_if_exists unique_index(:cart_lines, [:variant_id, :cart_id],
                     name: "cart_lines_unique_variant_index"
                   )

    drop constraint(:cart_lines, "cart_lines_variant_id_fkey")

    drop constraint(:cart_lines, "cart_lines_cart_id_fkey")

    drop table(:cart_lines)

    drop table(:carts)
  end
end
