package supportgroup

import (
	"errors"

	"hfb_sys/backend/internal/model"

	"gorm.io/gorm"
)

func PickSupportAdmin(tx *gorm.DB, groupCode string) (uint64, error) {
	var row struct {
		ID uint64
	}
	err := tx.Table("chat_support_groups AS g").
		Select("au.id").
		Joins("JOIN chat_support_group_members AS gm ON gm.group_id = g.id").
		Joins("JOIN admin_users AS au ON au.id = gm.admin_user_id").
		Where("g.code = ? AND g.status = ? AND au.status = ?", groupCode, "active", "active").
		Order(`CASE au.support_status WHEN 'online' THEN 0 WHEN 'busy' THEN 1 ELSE 2 END,
			(
				SELECT COUNT(1)
				FROM chat_participants AS cp
				WHERE cp.participant_type = 'admin'
				  AND cp.role = 'support'
				  AND cp.participant_id = au.id
			) ASC,
			au.id ASC`).
		Limit(1).
		Scan(&row).Error
	if err != nil {
		return 0, err
	}
	if row.ID > 0 {
		return row.ID, nil
	}
	return fallbackSupportAdmin(tx)
}

func fallbackSupportAdmin(tx *gorm.DB) (uint64, error) {
	var admin model.AdminUser
	err := tx.Table("admin_users AS au").
		Select("au.*").
		Joins("JOIN admin_user_roles AS aur ON aur.admin_user_id = au.id").
		Joins("JOIN roles AS r ON r.id = aur.role_id").
		Where("au.status = ? AND r.code = ?", "active", "cs").
		Order("CASE au.support_status WHEN 'online' THEN 0 WHEN 'busy' THEN 1 ELSE 2 END, au.id ASC").
		Limit(1).
		First(&admin).Error
	if err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return 0, nil
		}
		return 0, err
	}
	return admin.ID, nil
}
