package cvt

import (
	"encoding/json"
	"strings"

	maintent "github.com/tidbcloud/devops/entity/maintenance"

	maintmod "github.com/tidbcloud/devops/models/maintenance"
)

type m2e struct{}

func (cvt m2e) ClusterMaintenance(m *maintmod.ClusterMaintenance) *maintent.ClusterMaintenanceInRepo {
	e := &maintent.ClusterMaintenanceInRepo{
		ID:                       m.ID.Uint64(),
		LarkNotifiedAt:           m.LarkNotifiedAt,
		InstanceID:               m.InstanceID,
		ScheduledApplyTime:       m.ScheduledApplyTime,
		LastNotifiedCustomerDate: m.LastNotifiedCustomerDate,
	}
	return e
}

func (cvt m2e) ClusterOpsMaintenanceWindow(m *maintmod.ClusterOpsMaintenanceWindow) *maintent.ClusterOpsMaintenanceWindow {
	e := &maintent.ClusterOpsMaintenanceWindow{
		ID:        m.ID.Uint64(),
		ClusterID: m.ClusterID,
		CreatedAt: m.CreatedAt,
		UpdatedAt: m.UpdatedAt,
	}

	if m.Windows != nil {
		windows := []maintent.ClusterOpsMaintenanceWindowSlot{}
		if err := json.Unmarshal(m.Windows, &windows); err != nil {
			panic(err)
		}
		e.Windows = windows
	}

	if m.Approvers != "" {
		approvers := strings.Split(m.Approvers, ",")
		e.Approvers = make([]string, 0, len(approvers))
		for _, approver := range approvers {
			approver = strings.TrimSpace(approver)
			if approver == "" {
				continue
			}
			e.Approvers = append(e.Approvers, approver)
		}
	} else {
		e.Approvers = []string{}
	}

	return e
}

func (cvt m2e) OpsExecutionWindow(m *maintmod.OpsExecutionWindow) *maintent.OpsExecutionWindow {
	e := &maintent.OpsExecutionWindow{
		ID:        m.ID.Uint64(),
		CreatedAt: m.CreatedAt.Unix(),
		StartAt:   m.StartAt.Unix(),
		EndAt:     m.EndAt.Unix(),
	}
	if m.UpdatedAt != nil {
		e.UpdatedAt = m.UpdatedAt.Unix()
	}

	return e
}
