package db

import "olympus/oncall/backend/pkg/log"

// get all the categories that one can edit.
func GetAuth(email string) ([]int, map[int]string, error) {
	const SELECT_ENGINEER_ID_BY_EMAIL = `
		select
			engineer_id
		from
			engineers
		where
			email = ?
		limit 1`
	var engineerId int
	res := GetDB().Raw(SELECT_ENGINEER_ID_BY_EMAIL, email).Scan(&engineerId)
	if res.Error != nil {
		return nil, nil, res.Error
	}
	const SELECT_AUTH_CATEGORY_BY_ENGINEER_ID = `
		select
			category_id
		from
			auth
		where
			engineer_id = ?
	`
	var categories []int
	res = GetDB().Raw(SELECT_AUTH_CATEGORY_BY_ENGINEER_ID, engineerId).Scan(&categories)
	if res.Error != nil {
		return nil, nil, res.Error
	}
	global := false
	for _, category := range categories {
		if category == 0 {
			global = true
		}
	}
	allCategoriesWithName, err := GetAllCategoriesWithName()
	if err != nil {
		return nil, nil, res.Error
	}
	// if global, the user can edit all the categories.

	if global {
		var allCategories []int
		for k := range allCategoriesWithName {
			allCategories = append(allCategories, k)
		}
		return allCategories, allCategoriesWithName, nil
	}
	return categories, allCategoriesWithName, nil
}

// get all the categories that needs handling OnCall.
func GetAllCategoriesWithName() (map[int]string, error) {
	const GET_ALL_ONCALL_CATEGORIES = `
		select
			c.category_id as category_id,
			c.category_name as category_name
		from
			policies as p
			left join categories as c on c.category_id = p.category_id
		where
			c.enable = 1`
	type CategoryWithName struct {
		CategoryId   int    `gorm:"column:category_id"`
		CategoryName string `gorm:"column:category_name"`
	}
	cagegoriesWithName := make([]CategoryWithName, 0)
	res := GetDB().Raw(GET_ALL_ONCALL_CATEGORIES).Scan(&cagegoriesWithName)
	if res.Error != nil {
		return nil, res.Error
	}

	result := make(map[int]string)
	for _, v := range cagegoriesWithName {
		result[v.CategoryId] = v.CategoryName
	}
	return result, nil
}

func GetCategoriesByEmail(email string) ([]int, error) {
	const GET_CATEGORIES_BY_EMAIL = `
		select
			category_id
		from
			engineers natural
			join teams
		where
			engineers.email = ?
			and available = 1`
	var categories []int
	res := GetDB().Raw(GET_CATEGORIES_BY_EMAIL, email).Scan(&categories)
	if res.Error != nil {
		log.Error("msg", "error when get categories by email", "error info", res.Error)
	}
	return categories, nil
}
