package models

import (
    "sync"
    "time"
)

type TaskStatus string

const (
    TaskPending TaskStatus = "pending"
    TaskRunning TaskStatus = "running"
    TaskSuccess TaskStatus = "success"
    TaskFailed  TaskStatus = "failed"
)

type DeviceTaskStatus struct {
    DeviceID string     `json:"device_id"`
    Status   TaskStatus `json:"status"`
    Progress float64    `json:"progress"`
    Error    string     `json:"error"`
}

type Task struct {
    ID          string                       `json:"task_id"`
    Type        string                       `json:"type"`
    DeviceIDs   []string                     `json:"device_ids"`
    Payload     interface{}                  `json:"payload"`
    Status      TaskStatus                   `json:"status"`
    Devices     map[string]*DeviceTaskStatus `json:"devices"`
    CreatedAt   string                       `json:"created_at"`
    CompletedAt string                       `json:"completed_at"`
    Mu          sync.RWMutex                 `json:"-"`
}

func NewTask(id, t string, deviceIDs []string, payload interface{}) *Task {
    devices := make(map[string]*DeviceTaskStatus)
    for _, did := range deviceIDs {
        devices[did] = &DeviceTaskStatus{
            DeviceID: did,
            Status:   TaskPending,
        }
    }
    return &Task{
        ID:        id,
        Type:      t,
        DeviceIDs: deviceIDs,
        Payload:   payload,
        Status:    TaskPending,
        Devices:   devices,
        CreatedAt: time.Now().Format("2006-01-02 15:04:05"),
    }
}
