defmodule DaProductApp.Repo.Migrations.CreateUsersAuthTables do
  use Ecto.Migration

  def up do
    execute("""
    CREATE TABLE users (
      id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
      email VARCHAR(160) NOT NULL,
      hashed_password VARCHAR(255) NOT NULL,
      confirmed_at DATETIME,
      inserted_at DATETIME NOT NULL,
      updated_at DATETIME NOT NULL,
      UNIQUE KEY unique_email (email)
    ) ENGINE=InnoDB
    """)

    execute("""
    CREATE TABLE users_tokens (
      id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
      user_id BIGINT UNSIGNED NOT NULL,
      token BINARY(32) NOT NULL,
      context VARCHAR(255) NOT NULL,
      sent_to VARCHAR(255),
      inserted_at DATETIME NOT NULL,
      UNIQUE KEY unique_context_token (context, token),
      INDEX idx_user_id (user_id),
      CONSTRAINT fk_user_token FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
    ) ENGINE=InnoDB
    """)
  end

  def down do
    execute("DROP TABLE IF EXISTS users_tokens")
    execute("DROP TABLE IF EXISTS users")
  end
end
