package repository

import (
	"time"

	"hyapp-admin-server/internal/model"
)

func (s *Store) DashboardOverview() (*DashboardOverview, error) {
	var usersTotal, activeUsers, lockedUsers, disabledUsers int64
	if err := s.db.Model(&model.User{}).Count(&usersTotal).Error; err != nil {
		return nil, err
	}
	if err := s.db.Model(&model.User{}).Where("status = ?", model.UserStatusActive).Count(&activeUsers).Error; err != nil {
		return nil, err
	}
	if err := s.db.Model(&model.User{}).Where("status = ?", model.UserStatusLocked).Count(&lockedUsers).Error; err != nil {
		return nil, err
	}
	if err := s.db.Model(&model.User{}).Where("status = ?", model.UserStatusDisabled).Count(&disabledUsers).Error; err != nil {
		return nil, err
	}
	var rolesTotal, menuTotal, logsToday, unreadNotifications int64
	if err := s.db.Model(&model.Role{}).Count(&rolesTotal).Error; err != nil {
		return nil, err
	}
	if err := s.db.Model(&model.Menu{}).Where("visible = ?", true).Count(&menuTotal).Error; err != nil {
		return nil, err
	}
	now := time.Now().UTC()
	todayMS := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, time.UTC).UnixMilli()
	if err := s.db.Model(&model.OperationLog{}).Where("created_at_ms >= ?", todayMS).Count(&logsToday).Error; err != nil {
		return nil, err
	}
	if err := s.db.Model(&model.Notification{}).Where("read_at_ms IS NULL").Count(&unreadNotifications).Error; err != nil {
		return nil, err
	}

	var notifications []model.Notification
	if err := s.db.Where("read_at_ms IS NULL").Order("created_at_ms DESC").Limit(3).Find(&notifications).Error; err != nil {
		return nil, err
	}
	alerts := make([]map[string]string, 0, len(notifications))
	for _, item := range notifications {
		alerts = append(alerts, map[string]string{
			"type": item.Level,
			"name": item.Title,
			"desc": item.Content,
			"time": time.UnixMilli(item.CreatedAtMS).UTC().Format("15:04"),
		})
	}

	return &DashboardOverview{
		UsersTotal:          int(usersTotal),
		ActiveUsers:         int(activeUsers),
		LockedUsers:         int(lockedUsers),
		DisabledUsers:       int(disabledUsers),
		RolesTotal:          int(rolesTotal),
		MenuTotal:           int(menuTotal),
		LogsToday:           int(logsToday),
		UnreadNotifications: int(unreadNotifications),
		Series: map[string][]int{
			"users":         {int(usersTotal), int(activeUsers), int(lockedUsers), int(disabledUsers)},
			"operations":    {int(logsToday)},
			"notifications": {int(unreadNotifications)},
		},
		Alerts:      alerts,
		UpdatedAtMS: now.UnixMilli(),
	}, nil
}
