package organizationimp

import (
	"encoding/json"
	"errors"
	"net/http"

	"github.com/tech/sendico/pkg/api/http/response"
	"github.com/tech/sendico/pkg/merrors"
	"github.com/tech/sendico/pkg/model"
	"github.com/tech/sendico/pkg/mutil/mzap"
	"github.com/tech/sendico/server/interface/api/sresponse"
	mutil "github.com/tech/sendico/server/internal/mutil/param"
	"go.uber.org/zap"
)

func (a *OrganizationAPI) list(r *http.Request, account *model.Account, accessToken *sresponse.TokenData) http.HandlerFunc {
	orgs, err := a.db.List(r.Context(), *account.GetID(), nil)
	if errors.Is(err, merrors.ErrNoData) || (len(orgs) == 0) {
		a.logger.Debug("Organizations not found", zap.Error(err), mzap.StorableRef(account))
		return response.NotFound(a.logger, a.Name(), "orgnizations not found")
	}
	if err != nil {
		a.logger.Warn("Failed to fetch organizations", zap.Error(err))
		return response.Internal(a.logger, a.Name(), err)
	}
	return sresponse.Organizations(a.logger, orgs, accessToken)
}

func (a *OrganizationAPI) get(r *http.Request, account *model.Account, accessToken *sresponse.TokenData) http.HandlerFunc {
	orgRef, err := mutil.GetOrganizationRef(r)
	if err != nil {
		a.logger.Warn("Failed to parse organization id", zap.Error(err), zap.String("organization_ref", mutil.GetOrganizationID(r)))
		return response.BadReference(a.logger, a.Name(), mutil.OrganizationRefName(), mutil.GetOrganizationID(r), err)
	}

	var org model.Organization
	if err := a.db.Get(r.Context(), *account.GetID(), orgRef, &org); err != nil {
		if errors.Is(err, merrors.ErrNoData) {
			a.logger.Debug("Organization not found", mzap.ObjRef("organization_ref", orgRef), zap.Error(err))
			return response.NotFound(a.logger, a.Name(), "organization with given id not found")
		}
		a.logger.Error("Error fetching organization", mzap.ObjRef("organization_ref", orgRef), zap.Error(err))
		return response.Internal(a.logger, a.Name(), err)
	}

	return sresponse.Organization(a.logger, &org, accessToken)
}

func (a *OrganizationAPI) update(r *http.Request, acccount *model.Account, accessToken *sresponse.TokenData) http.HandlerFunc {
	var org model.OrganizationBase
	if err := json.NewDecoder(r.Body).Decode(&org); err != nil {
		a.logger.Warn("Failed to decode organization when updating settings", zap.Error(err))
		return response.BadPayload(a.logger, a.Name(), err)
	}

	ctx := r.Context()
	var orgStored model.Organization
	if err := a.db.Get(ctx, *acccount.GetID(), *org.GetID(), &orgStored); err != nil {
		a.logger.Warn("Failed to fetch organization for update", zap.Error(err), mzap.StorableRef(&org), mzap.StorableRef(acccount))
		return response.Auto(a.logger, a.Name(), err)
	}

	orgStored.OrganizationBase = org
	if err := a.db.Update(r.Context(), *acccount.GetID(), &orgStored); err != nil {
		a.logger.Warn("Error fetching organization", mzap.StorableRef(&org), zap.Error(err))
		return response.Internal(a.logger, a.Name(), err)
	}

	return sresponse.Organization(a.logger, &orgStored, accessToken)
}
