//  Vikunja is a todo-list application to facilitate your life.
//  Copyright 2019 Vikunja and contributors. All rights reserved.
//
//  This program is free software: you can redistribute it and/or modify
//  it under the terms of the GNU General Public License as published by
//  the Free Software Foundation, either version 3 of the License, or
//  (at your option) any later version.
//
//  This program is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//  GNU General Public License for more details.
//
//  You should have received a copy of the GNU General Public License
//  along with this program.  If not, see <https://www.gnu.org/licenses/>.

package migration

import (
	"code.vikunja.io/api/pkg/utils"
	"github.com/go-xorm/xorm"
	"src.techknowlogick.com/xormigrate"
)

type team20190525101422 struct {
	ID          int64  `xorm:"int(11) autoincr not null unique pk"`
	UID         string `xorm:"varchar(32) null"`
	Name        string `xorm:"varchar(250) not null"`
	Description string `xorm:"varchar(250)"`
	CreatedByID int64  `xorm:"int(11) not null INDEX"`
	Created     int64  `xorm:"created"`
	Updated     int64  `xorm:"updated"`
}

// TableName returns a pretty table name
func (team20190525101422) TableName() string {
	return "teams"
}

func init() {
	migrations = append(migrations, &xormigrate.Migration{
		ID:          "20190525101422",
		Description: "Add uids to teams",
		Migrate: func(tx *xorm.Engine) error {
			err := tx.Sync2(team20190525101422{})
			if err != nil {
				return err
			}

			// get all current teams and generate a random uid for them
			var allTeams []*team20190525101422
			err = tx.Find(&allTeams)
			if err != nil {
				return err
			}

			for _, t := range allTeams {
				t.UID = utils.MakeRandomString(32)
				_, err = tx.Where("id = ?", t.ID).Update(t)
				if err != nil {
					return err
				}
			}

			return nil
		},
		Rollback: func(tx *xorm.Engine) error {
			return dropTableColum(tx, "teams", "uid")
		},
	})
}
