package cvt

import (
	"time"

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

type e2m struct{}

func (cvt e2m) RemediationTicket(e *entity.RemediationTicket) *mod.RemediationTicket {
	mod := &mod.RemediationTicket{
		Updatable: base.Updatable{
			Base: base.Base{ID: base.ID(e.ID)},
		},

		AssociatedIncidentId: e.AssociatedIncidentId,
		Applicant:            e.ApplicantEmail,

		// State fields
		Status:             string(e.Status),
		CurrentResponsible: e.CurrentResponsible,
		ApprovalID:         (*base.ID)(&e.ApprID),

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

		// Region TSE Fields
		RootCauseFromGS: e.RootCauseFromGS,

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

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

		// Deprecated Fields, will remove in the future
		Reason:                 (*string)(e.Reason),
		ReportLink:             e.ReportLink,
		CalculatedCompensation: e.CalculatedCompensation,
		OverflowPercentage:     e.OverflowPercentage,

		ClosedAt: cvtTsToTime(e.ClosedAt),
	}

	if e.Phase != nil {
		mod.CurrentPhase = *e.Phase
	}

	return mod
}

func (cvt e2m) RemediationTicketPhaseApproval(e *entity.RemediationTicketPhaseApproval) *mod.RemediationTicketApprovals {
	mod := &mod.RemediationTicketApprovals{
		Base: base.Base{ID: base.ID(e.Id)},

		TicketId:   e.TicketId,
		FromPhase:  e.FromPhase,
		ToPhase:    e.ToPhase,
		ApprovalID: (*base.ID)(&e.ApprovalID),
		Message:    e.Message,
	}

	return mod
}

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