package database

import (
	"git.schreifuchs.ch/schreifuchs/warehouse/api"
	"git.schreifuchs.ch/schreifuchs/warehouse/model"
)

func (db *DB) InsertBucket(bucket *model.Bucket) error {
	return db.conn.Create(bucket).Error
}

func (db *DB) FindApiBuckets(limit, offset int) (buckets []api.Bucket, err error) {
	err = db.conn.Model(&model.Bucket{}).Limit(limit).Offset(offset).Find(&buckets).Error
	return
}
func (db *DB) FindBucketByName(name string) (bucket model.Bucket, err error) {
	err = db.conn.First(&bucket).Where("name = ?", name).Error
	return
}

func (db *DB) FindBucketIdByName(name string) (id uint, err error) {
	b := &model.Bucket{}
	err = db.conn.Select("id").First(b).Error

	return b.ID, err
}

func (db *DB) DeleteBucket(id uint) error {
	return db.conn.Delete(&model.Bucket{}, id).Error
}
func (db *DB) DeleteBucketByName(name string) error {
	return db.conn.Delete(&model.Bucket{}).Where("name = ?", name).Error
}

func (db *DB) FindObjectByKey(bucketName, key string) (object *model.Object, err error) {
	bid, err := db.FindBucketIdByName(bucketName)
	if err != nil {
		return
	}

	err = db.conn.Find(object).Where("key = ? AND bucket_id = ?", key, bid).Error

	return

}

func (db *DB) DeleteObjectByKey(bucketName, key string) (err error) {
	bid, err := db.FindBucketIdByName(bucketName)
	if err != nil {
		return
	}

	err = db.conn.Delete(&model.Object{}).Where("key = ? AND bucket_id = ?", key, bid).Error

	return
}
