package app

import (
	"fmt"

	"code.tnxs.net/taxnexus/lib/api/crm/crm_client/companies"
)

// GetCompany is a first class object retrieval function
func GetCompany(id string, principal *User) *Company {
	if id == "" {
		return nil
	}
	c, ok := companyCache.get(id)
	if ok {
		return c
	}
	c, err := GetCompanyByID(id, principal)
	if err != nil {
		return nil
	}
	return c
}

// GetCompanyByID is a first class object retrieval function
func GetCompanyByID(key string, principal *User) (*Company, error) {
	sugar.Debugf("app.getCompanyByID: 📥")
	if key == "" {
		return nil, fmt.Errorf("app.getCompanyByID: 💣 ⛔ key is blank")
	}
	cacheObj, ok := companyCache.get(key)
	if ok {
		sugar.Debugf("app.getCompanyByID: 👍 🎯 📤")
		return cacheObj, nil
	}
	params := companies.NewGetCompaniesParamsWithTimeout(getTimeout)
	params.CompanyID = &key
	response, err := crmClient.Companies.GetCompanies(params, principal.Auth)
	if err != nil {
		return nil, err
	}
	var obj *Company
	for _, itm := range response.Payload.Data { // single iteration execution
		obj = UnMarshalCompany(itm, principal)
	}
	finalObj := obj.Enrich(principal)
	companyCache.put(key, finalObj)
	sugar.Debugf("app.getCompanyByID: 👍 🆕 📤")
	return finalObj, nil
}

const defaultCompanyID = "6ff8326f-79b7-40ae-afc7-390eca182b1b" // todo #3 Don't hardcode company ID

// GetDefaultCompany returns the default company
func GetDefaultCompany(principal *User) *Company {
	return GetCompany(defaultCompanyID, principal)
}

// Enrich adds subordinate objects to a first class object and returns a copy
func (obj *Company) Enrich(principal *User) *Company {
	return &Company{
		ID:                  obj.ID,
		Account:             GetAccount(obj.AccountID, principal),
		AccountID:           obj.AccountID,
		AccountNumberPrefix: obj.AccountNumberPrefix,
		AdvancePeriodID:     obj.AdvancePeriodID,
		BillingAddress:      obj.BillingAddress,
		BillingAdvice:       obj.BillingAdvice,
		BillingContactID:    obj.BillingContactID,
		BillingContact:      GetContact(obj.BillingContactID, principal),
		BillingEmail:        obj.BillingEmail,
		BillingPhone:        obj.BillingPhone,
		BillingWebsite:      obj.BillingWebsite,
		CoaTemplateID:       obj.CoaTemplateID,
		ColorAccent1:        obj.ColorAccent1,
		ColorAccent2:        obj.ColorAccent2,
		ColorPrimary:        obj.ColorPrimary,
		ClosedPeriodID:      obj.ClosedPeriodID,
		CreatedByID:         obj.CreatedByID,
		CreatedDate:         obj.CreatedDate,
		CurrentPeriodID:     obj.CurrentPeriodID,
		CurrentPeriodStatus: obj.CurrentPeriodStatus,
		CustomerSuccessID:   obj.CustomerSuccessID,
		CustomerSuccess:     GetContact(obj.CustomerSuccessID, principal),
		DateClosed:          obj.DateClosed,
		DefaultAddress:      obj.DefaultAddress,
		DefaultCompany:      obj.DefaultCompany,
		FontBody:            obj.FontBody,
		FontHeading:         obj.FontHeading,
		FontHeadingNarrow:   obj.FontHeadingNarrow,
		FontLink:            obj.FontLink,
		FontMono:            obj.FontMono,
		International:       obj.International,
		LastAccountNumber:   obj.LastAccountNumber,
		LastModifiedByID:    obj.LastModifiedByID,
		LastModifiedDate:    obj.LastModifiedDate,
		LastTaxtypeNumber:   obj.LastTaxtypeNumber,
		Logo:                obj.Logo,
		Name:                obj.Name,
		OwnerID:             obj.OwnerID,
		Preparer:            GetContact(obj.PreparerID, principal),
		PreparerID:          obj.PreparerID,
		PricebookID:         obj.PricebookID,
		TenantID:            obj.TenantID,
		UserTechLead:        GetContact(obj.UserTechLeadID, principal),
		UserTechLeadID:      obj.UserTechLeadID,
	}
}
