package converter

import (
	"time"

	v1 "github.com/AlchemyTelcoSolutions/callisto-so-bff/api/v1"
	"github.com/AlchemyTelcoSolutions/callisto-so-bff/internal/domain/model"
	SOProto "github.com/AlchemyTelcoSolutions/proto/gen/go/callisto/so/v1"
	"google.golang.org/protobuf/types/known/timestamppb"
)

type priorityBFF uint32

const (
	PRIORITY_UNSPECIFIED = iota
	PRIORITY_STANDARD
	PRIORITY_EXPRESS
	PRIORITY_AUTO
)

func ToProtoFromNoteRequest(req *model.UpdateNoteData) *SOProto.AddNoteRequest {
	addNoteRequest := &SOProto.AddNoteRequest{
		OrderRef:  req.OrderReference,
		CreatedAt: timestamppb.New(req.CreatedAt),
		CreatedBy: uint64(req.UserID),
		Details:   req.Note,
	}
	return addNoteRequest
}

func ToAddShipmentFromReq(req *v1.UpdateSaleOrderMultipartBody) (*model.AddShipmentData, error) {
	var isCollection bool
	dispatched := req.ShippedDate
	if req.CollectDate != nil {
		dispatched = req.CollectDate
		isCollection = true
	}
	var dispatchedDate *time.Time = nil
	if dispatched != nil {
		date, err := time.Parse("2006-01-02 15:04:05", *dispatched)
		if err != nil {
			return nil, err
		}
		dispatchedDate = &date
	}

	shipmentData := &model.AddShipmentData{
		DispatchedAt: dispatchedDate,
		IsCollection: isCollection,
		TrackingCode: strOrEmpty(req.TrackingCode),
		TrackingUrl:  strOrEmpty(req.TrackingURL),
		CreatedAt:    time.Now(),
		// values in proto are different that in callisto-api
		// added when that will be resolved
		// CourierRef:   req.CourierRef,
	}
	if req.ShippingMethodID != nil {
		shipmentData.Priority = uint32(priorityBFF(*req.ShippingMethodID))
	}
	if req.NoAirbill != nil {
		shipmentData.NoAirbill = *req.NoAirbill == 1
	}
	return shipmentData, nil
}

func ToProtoFromShipmentRequest(req *model.AddShipmentData) *SOProto.AddShipmentRequest {
	shipment := &SOProto.Shipment{
		OrderRef:     req.OrderReference,
		IsCollection: req.IsCollection,
		TrackingCode: req.TrackingCode,
		TrackingUrl:  req.TrackingUrl,
		DispatchedAt: timestamppb.New(*req.DispatchedAt),
		CreatedAt:    timestamppb.New(req.CreatedAt),
		CreatedBy:    uint64(req.UserID),
		Priority:     SOProto.Shipment_Priority(req.Priority),
		NoWaybill:    req.NoAirbill,
		// values in proto are different that in callisto-api
		// added when that will be resolved
		// CourierRef:   req.CourierRef,
	}

	return &SOProto.AddShipmentRequest{Shipment: shipment}
}

func ToAddDocumentToProto(data *model.AddDocumentData) *SOProto.AddDocumentRequest {
	return &SOProto.AddDocumentRequest{
		OrderRef:     data.OrderReference,
		DocumentType: SOProto.Doctype(data.DocumentType),
		Url:          data.Url,
		Hash:         data.Hash,
		CreatedBy:    uint64(data.CreatedBy),
	}
}

func strOrEmpty(str *string) string {
	if str != nil {
		return *str
	}
	return ""
}
