package app

import (
	"database/sql"
	"time"

	"code.tnxs.net/taxnexus/lib/api/devops/devops_models"
	"github.com/google/uuid"
)

// UnMarshalDatabase decodes swagger to a first class object
func UnMarshalDatabase(s *devops_models.Database) *Database {
	if s.ID == "" {
		s.ID = uuid.New().String()
	}
	createdDate, e0 := time.Parse(dateTimeFormat, s.CreatedDate)
	lastModfiedDate, e1 := time.Parse(dateTimeFormat, s.LastModifiedDate)
	return &Database{
		ID:               s.ID,
		Active:           s.Active,
		ClusterID:        s.ClusterID,
		CreatedByID:      s.CreatedByID,
		DatabaseName:     s.DatabaseName,
		DSN:              s.DSN,
		LastModifiedByID: s.LastModifiedByID,
		Microservices:    s.Microservices,
		Status:           s.Status,
		TenantID:         s.TenantID,
		Type:             s.Type,
		CreatedDate: sql.NullTime{
			Time:  createdDate,
			Valid: e0 == nil,
		},
		LastModifiedDate: sql.NullTime{
			Time:  lastModfiedDate,
			Valid: e1 == nil,
		},
	}
}

// MarshalToSwagger encodes a first class object to swagger
func (obj *Database) MarshalToSwagger() *devops_models.Database {
	return &devops_models.Database{
		ID:               obj.ID,
		Active:           obj.Active,
		ClusterID:        obj.ClusterID,
		CreatedByID:      obj.CreatedByID,
		CreatedDate:      obj.CreatedDate.Time.Format(dateTimeFormat),
		DatabaseName:     obj.DatabaseName,
		DSN:              obj.DSN,
		LastModifiedByID: obj.LastModifiedByID,
		LastModifiedDate: obj.LastModifiedDate.Time.Format(dateTimeFormat),
		Microservices:    obj.Microservices,
		Status:           obj.Status,
		TenantID:         obj.TenantID,
		Type:             obj.Type,
	}
}
