package main

import (
	"encoding/json"
	"testing"
	"time"
)

func TestCreateEntity(t *testing.T) {
	SetupConfig()
	e := crmdLead{}
	e.FirstName = "ff" + time.Now().Format("2006-jan-02 03:04:05")
	e.LastName = "ll"
	e.Password = "pp"
	e.Status = "New"
	b, _ := json.Marshal(e)

	//Create
	entity, _ := createEntity("Lead", b)
	lead1, ok := entity.(crmdLead)
	AssertEqual(t, ok, true, "entity type should be crmdLead")

	//Read
	lead2, _ := crmGetLead(lead1.ID)
	AssertEqual(t, lead2.ID, lead1.ID, "lead id should be equal")

	//Update
	e.Password = "newpass"
	b, _ = json.Marshal(e)
	entity, _ = updateEntity("Lead", lead2.ID, b)
	lead3 := entity.(crmdLead)

	AssertEqual(t, lead3.ID, lead1.ID, "should be same lead")
	AssertEqual(t, lead3.Password, "newpass", "password should have been changed")
	AssertEqual(t, lead1.Password, "pp", "old password should be PP")

	//Delete this test lead.
	deleted, _ := deleteEntity("Lead", lead1.ID)
	AssertEqual(t, deleted, true, "record should be deleted")

}

func TestCreateDuplicate(t *testing.T) {
	SetupConfig()
	e := crmdLead{}
	e.FirstName = "ff" + time.Now().Format("2006-jan-02 03:04:05")
	e.LastName = "ll"
	e.Password = "pp"
	e.Status = "New"
	e.WechatHitxyID = "someopenid"
	b, _ := json.Marshal(e)

	//create
	entity, _ := createEntity("Lead", b)
	lead1 := entity.(crmdLead)

	//Read
	entity, _ = crmGetEntity("Lead", lead1.ID)
	lead2 := entity.(crmdLead)
	AssertEqual(t, lead1.ID, lead2.ID, "lead should have been created successfully")

	//try to create it again
	entity, err := createEntity("Lead", b)
	AssertEqual(t, err == nil, false, "should have error for duplicates")
	AssertEqual(t, isErrIndicateDuplicate(err), true, "the err should be duplicate error")
}

func TestCreateEntityServerNotFound(t *testing.T) {
	SetupConfig()
	crmSite = "https://not-exist.hitxy.org.au/" //

	e := crmdLead{}
	e.FirstName = "ff" + time.Now().Format("2006-jan-02 03:04:05")
	e.LastName = "ll"
	e.Password = "pp"
	e.Status = "New"
	e.WechatHitxyID = "someopenid"
	b, _ := json.Marshal(e)
	entity, err := createEntity("Lead", b)
	AssertEqual(t, isErrIndicateDuplicate(err), false, "this should not be a duplicate error")
	AssertEqual(t, entity, nil, "should not be able to create entity, it should be nil")

}
