package common

import (
	"crypto/x509"
	"encoding/pem"
	"fmt"
	"time"

	"github.com/fiskerinc/cloud-services/pkg/common/dbbasemodel"
)

// CertificateRequest schema
const (
	CertCharging   string = "CHARGING"
	CertICC        string = "ICC"
	CertTBOX       string = "TBOX"
	CertAftersales string = "AFTERSALES"
)

type Certificate struct {
	PublicKey    string `json:"public_key"`
	CommonName   string `json:"-" validate:"required"`
	PrivateKey   string `json:"private_key,omitempty" pg:"-"`
	EncryptedKey []byte `json:"-" pg:"encrypted_key"`
	SerialNumber string `json:"serial_number" pg:",pk"`
	Type         string `json:"type"`
	Valid        bool   `json:"-" pg:",use_zero"`
	CreatedBy    string `json:"-" pg:"created_by"`
	dbbasemodel.DBModelBase
}

func (cert Certificate) String() string {
	return fmt.Sprintf("Certificate for Common Name:<%s>", cert.CommonName)
}

func (cert Certificate) IsExpiredOrInvalidAtTime(t time.Time, certDaysBeforeExp int) (bool, error) {
	if !cert.Valid {
		return true, nil
	}

	if cert.PublicKey != "" {
		p, _ := pem.Decode([]byte(cert.PublicKey))
		if p != nil {
			c, err := x509.ParseCertificate(p.Bytes)
			if err != nil {
				return true, err
			}

			day := c.NotAfter.AddDate(0, 0, 0-certDaysBeforeExp)
			if t.After(day) {
				return true, nil
			}
		}
	}

	return false, nil
}
