class CreateSaucyTables < ActiveRecord::Migration
  def self.up
    create_table :memberships do |table|
      table.integer  :account_id
      table.integer  :user_id
      table.boolean  :admin
      table.datetime :created_at
      table.datetime :updated_at
    end

    add_index :memberships, [:account_id, :user_id], :unique => true

    create_table :accounts do |table|
      table.belongs_to :plan
      table.string   :name
      table.string   :url
      table.datetime :created_at
      table.datetime :updated_at
    end
    add_index :accounts, :plan_id

    create_table :invitations do |table|
      table.string   :email
      table.integer  :account_id
      table.boolean  :admin
      table.datetime :created_at
      table.datetime :updated_at
    end

    add_index :invitations, [:account_id]

    create_table :permissions do |table|
      table.integer  :membership_id
      table.integer  :user_id
      table.integer  :project_id
      table.datetime :created_at
      table.datetime :updated_at
    end

    add_index :permissions, [:user_id, :project_id]
    add_index :permissions, [:membership_id, :project_id], :name => [:membership_and_project]

    create_table :projects do |table|
      table.string   :name
      table.integer  :account_id
      table.datetime :created_at
      table.datetime :updated_at
    end

    alter_table :users do |table|
      table.string :name, :default => ""
    end

    create_table :plans do |t|
      t.string :name
      t.integer :price

      t.timestamps
    end

    add_index :plans, :name

    create_table :invitations_projects, :id => false do |table|
      table.integer :invitation_id, :null => false
      table.integer :project_id, :null => false
    end

    add_index :invitations_projects, [:invitation_id, :project_id], :unique => true
  end

  def self.down
    remove_column :users, :name
    drop_table :invitations_projects
    drop_table :plans
    drop_table :projects
    drop_table :permissions
    drop_table :invitations
    drop_table :accounts
    drop_table :memberships
  end
end