package cvt

import (
	"strconv"
	"time"

	"github.com/tidbcloud/devops/entity"
	mod "github.com/tidbcloud/devops/models/remediationticket"
)

type m2e struct{}

func (cvt m2e) RemediationTicket(m *mod.RemediationTicket) *entity.RemediationTicket {
	var apprID uint64
	if m.ApprovalID == nil {
		apprID = 0
	} else {
		apprID = uint64(*m.ApprovalID)
	}

	cluster := ""
	if m.ClusterID != nil {
		cluster = strconv.FormatUint(*m.ClusterID, 10)
	}

	tenant := ""
	if m.TenantID != nil {
		tenant = strconv.FormatUint(*m.TenantID, 10)
	}

	e := &entity.RemediationTicket{
		ID: m.ID.Uint64(),

		AssociatedIncidentId: m.AssociatedIncidentId,
		ApplicantEmail:       m.Applicant,

		// State fields
		Status:             entity.RemediationTicketStatus(m.Status),
		Phase:              &m.CurrentPhase,
		ApprID:             apprID,
		CurrentResponsible: m.CurrentResponsible,

		// Create params
		BizRegion:       m.BizRegion,
		Customer:        m.CustomerName,
		ClusterType:     m.ClusterType,
		TenantID:        m.TenantID,
		ClusterID:       m.ClusterID,
		InfoFromCreator: m.InfoFromCreator,
		Month:           m.Month,

		// Region TSE Fields
		RootCauseFromGS: m.RootCauseFromGS,

		// Region SLA Owner Fields
		MonthlyUptimePercentage: m.MonthlyUptimePercentage,
		AccumulatedDownMinutes:  m.AccumulatedDownMinutes,
		RootCauseFromRDG:        m.RootCauseFromRDG,
		AccidentReportLink:      m.AccidentReportLink,
		GeneratedDocURL:         m.GeneratedDocURL,

		// Global Deal Desk Fields
		ClusterBilling:    m.ClusterBilling,
		PredefinedPercent: m.PredefinedPercent,
		ExtraPercent:      m.ExtraPercent,
		TotalCompensation: m.TotalCompensation,

		// Deprecated Fields, will be removed
		ReportLink:             m.ReportLink,
		CalculatedCompensation: m.CalculatedCompensation,
		OverflowPercentage:     m.OverflowPercentage,

		Version: m.UpdatedAt.Unix(), // TODO: use update time as version number, need more processing.

		CreatedAt: m.CreatedAt.Unix(),
		ClosedAt:  cvtTimeToTs(m.ClosedAt),

		Cluster: cluster,
		Tenant:  tenant,
	}

	if m.Reason != nil {
		num := entity.RemediationTicketReason(*m.Reason)
		e.Reason = &num
	}

	return e
}

func (cvt m2e) RemediationTicketPhaseApproval(m *mod.RemediationTicketApprovals) *entity.RemediationTicketPhaseApproval {
	e := &entity.RemediationTicketPhaseApproval{
		Id: m.ID.Uint64(),

		CreatedAt:  &m.CreatedAt,
		TicketId:   m.TicketId,
		FromPhase:  m.FromPhase,
		ToPhase:    m.ToPhase,
		Message:    m.Message,
		ApprovalID: m.ApprovalID.Uint64(),
	}

	return e
}

func cvtTimeToTs(t *time.Time) *int64 {
	if t == nil {
		return nil
	}
	ts := t.Unix()
	return &ts
}
