package permission

import (
	"context"

	"gateway/internal/model/permission/domain/enum"
	domperm "gateway/internal/model/permission/domain/usecase"
	"gateway/internal/svc"
	"gateway/internal/types"

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

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

// NewUpsertRoleMappingLogic returns the upsert-mapping logic.
func NewUpsertRoleMappingLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpsertRoleMappingLogic {
	return &UpsertRoleMappingLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

// UpsertRoleMapping creates or replaces an external→internal mapping.
func (l *UpsertRoleMappingLogic) UpsertRoleMapping(req *types.UpsertRoleMappingReq) (*types.RoleMappingData, error) {
	if l.svcCtx.PermissionRoleMapping == nil {
		return nil, errb.SysNotImplemented("permission module not configured")
	}
	actor, err := ActorFromContext(l.ctx)
	if err != nil {
		return nil, errb.AuthUnauthorized(err.Error()).WithCause(err)
	}
	rm, err := l.svcCtx.PermissionRoleMapping.Upsert(l.ctx, &domperm.UpsertMappingParam{
		TenantID:        actor.TenantID,
		ExternalSource:  enum.RoleSource(req.ExternalSource),
		ExternalKey:     req.ExternalKey,
		InternalRoleKey: req.InternalRoleKey,
	})
	if err != nil {
		return nil, err
	}
	return &types.RoleMappingData{
		ID:              rm.ID.Hex(),
		TenantID:        rm.TenantID,
		ExternalSource:  rm.ExternalSource.String(),
		ExternalKey:     rm.ExternalKey,
		InternalRoleID:  rm.InternalRoleID,
		InternalRoleKey: rm.InternalRoleKey,
		CreateAt:        rm.CreateAt,
		UpdateAt:        rm.UpdateAt,
	}, nil
}
