package db

import (
	"fmt"
	"olympus/oncall/backend/pkg/log"
	"strconv"
)

func GetCurrentWeekSchedule() (map[string][]string, error) {
	tmpWeekId, err := GetTempWeekId()
	if err != nil {
		return nil, err
	}
	const GET_CURRENT_ONCALL_INFORMATION_MAP = `
	select
			c1.category_name as category_name,
			email
		from
			categories as c1
			left join categories as c2 on c1.parent_category_id = c2.category_id,
			shift,
			engineers,
			t_week_id
		where
			c1.category_id = shift.category_id
			and shift.engineer_id = engineers.engineer_id
			and shift.week_id = ?
			and t_week_id.id = shift.week_id`

	type CurrentInformation struct {
		CategoryName string `gorm:"column:category_name"`
		Email        string `gorm:"column:email"`
	}

	currentInfs := make([]CurrentInformation, 0)
	tmpDecimal2, _ := strconv.ParseFloat(fmt.Sprintf("%.2f", tmpWeekId), 64)
	res := GetDB().Raw(GET_CURRENT_ONCALL_INFORMATION_MAP, tmpDecimal2).Scan(&currentInfs)
	if res.Error != nil {
		log.Error("msg", "error: get current info", "error info", res.Error)
	}

	resMap := make(map[string]([]string))

	for _, v := range currentInfs {
		if _, exist := resMap[v.CategoryName]; exist {
			resMap[v.CategoryName] = append(resMap[v.CategoryName], v.Email)
		} else {
			resMap[v.CategoryName] = make([]string, 0)
			resMap[v.CategoryName] = append(resMap[v.CategoryName], v.Email)
		}
	}
	return resMap, nil

}
