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

  def change do
    create table(:orders, primary_key: false) do
      add :id, :binary_id, primary_key: true
      add :order_number, :string, null: false
      add :stripe_session_id, :string
      add :stripe_payment_intent_id, :string
      add :payment_status, :string, null: false, default: "pending"
      add :customer_email, :string
      add :shipping_address, :map, default: %{}
      add :subtotal, :integer, null: false
      add :total, :integer, null: false
      add :currency, :string, null: false, default: "gbp"
      add :metadata, :map, default: %{}

      timestamps(type: :utc_datetime)
    end

    create unique_index(:orders, [:order_number])
    create unique_index(:orders, [:stripe_session_id])
    create index(:orders, [:payment_status])

    create table(:order_items, primary_key: false) do
      add :id, :binary_id, primary_key: true
      add :order_id, references(:orders, type: :binary_id, on_delete: :delete_all), null: false
      add :variant_id, :string, null: false
      add :product_name, :string, null: false
      add :variant_title, :string
      add :quantity, :integer, null: false
      add :unit_price, :integer, null: false

      timestamps(type: :utc_datetime)
    end

    create index(:order_items, [:order_id])
  end
end
