package db

import (
	"github.com/google/uuid"
	log "github.com/sirupsen/logrus"
	"gorm.io/gorm"

	"reichard.io/imagini/graph/model"
)

func (dbm *DBManager) CreateDevice(device *model.Device) error {
	log.Debug("[db] Creating device: ", device.Name)
	refreshKey := uuid.New().String()
	device.RefreshKey = &refreshKey
	err := dbm.db.Create(device).Error
	return err
}

func (dbm *DBManager) Device(device *model.Device) (int64, error) {
	var count int64
	err := dbm.db.Where(device).First(device).Count(&count).Error
	return count, err
}

func (dbm *DBManager) Devices(userID string, filters *model.DeviceFilter, page *model.Page, order *model.Order) ([]*model.Device, model.PageResponse, error) {
	// Initial User Filter
	tx := dbm.db.Session(&gorm.Session{}).Model(&model.Device{}).Where("user_id == ?", userID)

	// Dynamically Generate Base Query
	tx, pageResponse := dbm.generateBaseQuery(tx, filters, page, order)

	// Acquire Results
	var foundDevices []*model.Device
	err := tx.Find(&foundDevices).Error
	return foundDevices, pageResponse, err
}

func (dbm *DBManager) DeleteDevice(user *model.Device) error {
	return nil
}

func (dbm *DBManager) UpdateRefreshToken(device *model.Device, refreshToken string) error {
	return nil
}
