package system

import (
	"time"
	"wails-app/internal/global"
)

type DeviceStatus struct {
	ChannelName  string `json:"channel_name"`
	Direction    string `json:"direction"`
	DeviceName   string `json:"device_name"`
	DeviceStatus string `json:"device_status"`
}

type MonitorData struct {
	TotalSpaces int64          `json:"total_spaces"`
	UsedSpaces  int64          `json:"used_spaces"`
	InPark      int64          `json:"in_park"`
	TodayIncome float64        `json:"today_income"`
	TodayEntry  int64          `json:"today_entry"`
	TodayExit   int64          `json:"today_exit"`
	Devices     []DeviceStatus `json:"devices"`
}

type DashboardService struct{}

func (s *DashboardService) GetMonitorData() (MonitorData, error) {
	var d MonitorData
	today := time.Now().Format("2006-01-02")

	global.GVA_DB.Raw("SELECT COALESCE(SUM(capacity), 0) FROM parking_lot").Scan(&d.TotalSpaces)
	global.GVA_DB.Raw("SELECT COUNT(*) FROM vehicle_record WHERE exit_time IS NULL").Scan(&d.InPark)
	d.UsedSpaces = d.InPark

	global.GVA_DB.Raw("SELECT COALESCE(SUM(amount), 0) FROM payment_record WHERE paid_at >= ? AND paid_at < ?",
		today, today+" 23:59:59").Scan(&d.TodayIncome)

	global.GVA_DB.Raw("SELECT COUNT(*) FROM vehicle_record WHERE entry_time >= ? AND entry_time < ?",
		today, today+" 23:59:59").Scan(&d.TodayEntry)
	global.GVA_DB.Raw("SELECT COUNT(*) FROM vehicle_record WHERE exit_time >= ? AND exit_time < ?",
		today, today+" 23:59:59").Scan(&d.TodayExit)

	global.GVA_DB.Raw(`SELECT ch.channel_name, ch.direction,
		COALESCE(uhf.device_name, '-') as device_name,
		COALESCE(uhf.status, 'offline') as device_status
		FROM channel ch LEFT JOIN uhf_reader uhf ON uhf.channel_id = ch.id
		WHERE ch.deleted_at IS NULL ORDER BY ch.id`).Scan(&d.Devices)

	return d, nil
}
