//
//  tank
//
//  Import and Playlist Daemon for autoradio project
//
//
//  Copyright (C) 2017-2018 Christian Pointner <equinox@helsinki.at>
//
//  This file is part of tank.
//
//  tank 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
//  any later version.
//
//  tank 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 tank. If not, see <http://www.gnu.org/licenses/>.
//

package store

import (
	"errors"

	"github.com/jinzhu/gorm"
	"gopkg.in/gormigrate.v1"
)

func initialMigration(tx *gorm.DB) (err error) {
	err = tx.AutoMigrate(
		&Group{},
		&File{},
		&Playlist{},
		&PlaylistEntry{},
	).Error

	if err != nil {
		return
	}

	if err := tx.Model(File{}).AddForeignKey("group_name", "groups (name)", "CASCADE", "CASCADE").Error; err != nil {
		return err
	}
	if err := tx.Model(Playlist{}).AddForeignKey("group_name", "groups (name)", "CASCADE", "CASCADE").Error; err != nil {
		return err
	}
	if err := tx.Model(PlaylistEntry{}).AddForeignKey("playlist_id", "playlists (id)", "CASCADE", "CASCADE").Error; err != nil {
		return err
	}
	if err := tx.Model(PlaylistEntry{}).AddForeignKey("file_id", "files (id)", "RESTRICT", "CASCADE").Error; err != nil {
		return err
	}
	return nil
}

func (st *Store) initDBModel() (err error) {
	opts := gormigrate.DefaultOptions
	opts.TableName = migrationsTn
	m := gormigrate.New(st.db, opts, []*gormigrate.Migration{
		// for now everthing is done @ initialMigration()
		{
			ID:       "201806161853",
			Migrate:  func(tx *gorm.DB) error { return nil },
			Rollback: func(tx *gorm.DB) error { return nil },
		},
	})

	m.InitSchema(initialMigration)
	if err = m.Migrate(); err != nil {
		return errors.New("running database migrations failed: " + err.Error())
	}

	if err = st.db.Table(migrationsTn).Select("id").Order("id").Limit(1).Row().Scan(&st.revision); err != nil {
		return errors.New("fetching current database revision failed: " + err.Error())
	}
	return
}