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 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
	}

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