package queries_test

import (
	"testing"

	"github.com/fiskerinc/cloud-services/pkg/common"
	m "github.com/fiskerinc/cloud-services/pkg/common"
	"github.com/fiskerinc/cloud-services/pkg/db"
	"github.com/fiskerinc/cloud-services/pkg/db/queries"
	"github.com/fiskerinc/cloud-services/pkg/testhelper"
	"github.com/go-pg/pg/v10"
	"github.com/pkg/errors"
)

var publicTestCert = common.NewBinaryHex([]byte("9a1a6949d7f8a511df6e2e2771e444dbd6de97"))
var privTestCert = common.NewBinaryHex([]byte("cda02810bad1b6f1b8c6202234a424b7d5b9a1"))

func TestSignedImagesIntegration(t *testing.T) {
	t.Skip()
	query := setupSignedImages(t)
	testInsertSigningCert(t, query)
	testGetSigningCert(t, query)
	testDeleteSigningCert(t, query)
}

func setupSignedImages(t *testing.T) queries.SignedImagesInterface {
	instance := queries.SignedImages{}
	conn = instance.GetDBConn()
	conn.AddQueryHook(db.SQLLogger{})

	client := instance.GetClient()
	client.InitSchema([]interface{}{
		(*common.Issue)(nil),
	})

	return &instance
}

func testInsertSigningCert(t *testing.T, query queries.SignedImagesInterface) {
	cert := m.SupplierSigningCert{
		Supplier:    "TESTSUPPLER",
		KeyCert:     "sbc_key_4096",
		PublicCert:  publicTestCert,
		PrivateCert: privTestCert,
	}

	res, err := query.InsertSigningCert(cert)
	if err != nil {
		t.Errorf(testhelper.TestErrorTemplate, "SupplierSigningCert insert", "No error", err)
	}

	if res.RowsAffected() != 1 {
		t.Errorf(testhelper.TestErrorTemplate, "SupplierSigningCert insert RowsAffected", 1, res.RowsAffected())
	}
}

func testGetSigningCert(t *testing.T, query queries.SignedImagesInterface) {
	_, err := query.GetSigningCert("TESTSUPPLER", "verified_rsa4096_key")
	if !errors.Is(err, pg.ErrNoRows) {
		t.Errorf(testhelper.TestErrorTemplate, "GetSigningCert", pg.ErrNoRows, err)
	}

	cert, err := query.GetSigningCert("TESTSUPPLER", "sbc_key_4096")
	if err != nil {
		t.Errorf(testhelper.TestErrorTemplate, "GetSigningCert", pg.ErrNoRows, err)
	}

	if cert.PublicCert.String() != publicTestCert.String() {
		t.Errorf(testhelper.TestErrorTemplate, "GetSigningCert.PublicCert", publicTestCert.String(), cert.PublicCert.String())
	}

	if cert.PrivateCert.String() != privTestCert.String() {
		t.Errorf(testhelper.TestErrorTemplate, "GetSigningCert.PrivateCert", privTestCert, cert.PrivateCert)
	}
}

func testDeleteSigningCert(t *testing.T, query queries.SignedImagesInterface) {
	_, err := query.DeleteSigningCert(m.SupplierSigningCert{
		Supplier: "TESTSUPPLER",
		KeyCert:  "sbc_key_4096",
	})
	if err != nil {
		t.Errorf(testhelper.TestErrorTemplate, "DeleteSigningCert", nil, err)
	}
}
