package agent

import (
	"context"
	"time"

	"znc-server/app/main/api/internal/svc"
	"znc-server/app/main/api/internal/types"
	"znc-server/app/main/model"
	"znc-server/common/ctxdata"
	"znc-server/common/xerr"

	"github.com/pkg/errors"
	"github.com/zeromicro/go-zero/core/logx"
)

type GetAgentWithdrawalTaxExemptionLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewGetAgentWithdrawalTaxExemptionLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetAgentWithdrawalTaxExemptionLogic {
	return &GetAgentWithdrawalTaxExemptionLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *GetAgentWithdrawalTaxExemptionLogic) GetAgentWithdrawalTaxExemption(req *types.GetWithdrawalTaxExemptionReq) (resp *types.GetWithdrawalTaxExemptionResp, err error) {
	userID, err := ctxdata.GetUidFromCtx(l.ctx)
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.SERVER_COMMON_ERROR), "获取用户ID失败: %+v", err)
	}
	agent, err := l.svcCtx.AgentModel.FindOneByUserId(l.ctx, userID)
	if err != nil {
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "获取代理ID失败: %+v", err)
	}
	yearMonth := int64(time.Now().Year()*100 + int(time.Now().Month()))

	agentWithdrawalTaxExemption, err := l.svcCtx.AgentWithdrawalTaxExemptionModel.FindOneByAgentIdYearMonth(l.ctx, agent.Id, yearMonth)
	if err != nil {
		if errors.Is(err, model.ErrNotFound) {
			agentWithdrawalTaxExemption, err = l.createMonthlyExemption(agent.Id, yearMonth)
			if err != nil {
				return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "创建代理税务额度失败: %v", err)
			}
		} else {
			return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR), "获取代理税务额度失败: %+v", err)
		}
	}

	return &types.GetWithdrawalTaxExemptionResp{
		TotalExemptionAmount:     agentWithdrawalTaxExemption.TotalExemptionAmount,
		UsedExemptionAmount:      agentWithdrawalTaxExemption.UsedExemptionAmount,
		RemainingExemptionAmount: agentWithdrawalTaxExemption.RemainingExemptionAmount,
		TaxRate:                  l.svcCtx.Config.TaxConfig.TaxRate,
	}, nil
}
func (l *GetAgentWithdrawalTaxExemptionLogic) createMonthlyExemption(agentId int64, yearMonth int64) (*model.AgentWithdrawalTaxExemption, error) {
	exemption := &model.AgentWithdrawalTaxExemption{
		AgentId:                  agentId,
		YearMonth:                yearMonth,
		TotalExemptionAmount:     l.svcCtx.Config.TaxConfig.TaxExemptionAmount,
		UsedExemptionAmount:      0.00,
		RemainingExemptionAmount: l.svcCtx.Config.TaxConfig.TaxExemptionAmount,
	}

	result, err := l.svcCtx.AgentWithdrawalTaxExemptionModel.Insert(l.ctx, nil, exemption)
	if err != nil {
		return nil, err
	}

	id, _ := result.LastInsertId()
	exemption.Id = id
	return exemption, nil
}
