package applogic

import (
	"context"
	"fmt"

	"aijianzhan/platform/internal/authx"
	"aijianzhan/platform/internal/orgunitstore"
	"aijianzhan/platform/internal/svc"
	"aijianzhan/platform/internal/types"
)

type OrgUnitLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewOrgUnitLogic(ctx context.Context, svcCtx *svc.ServiceContext) *OrgUnitLogic {
	return &OrgUnitLogic{ctx: ctx, svcCtx: svcCtx}
}

func (l *OrgUnitLogic) List() ([]orgunitstore.OrgUnit, error) {
	if l.svcCtx.OrgUnits == nil {
		return nil, fmt.Errorf("org unit store unavailable")
	}
	return l.svcCtx.OrgUnits.List(l.ctx, authx.TenantID(l.ctx))
}

func (l *OrgUnitLogic) Create(req *types.OrgUnitCreateReq) (*orgunitstore.OrgUnit, error) {
	if l.svcCtx.OrgUnits == nil {
		return nil, fmt.Errorf("org unit store unavailable")
	}
	return l.svcCtx.OrgUnits.Create(l.ctx, authx.TenantID(l.ctx), orgunitstore.CreateInput{
		ParentID: req.ParentID,
		Name:     req.Name,
		Code:     req.Code,
	})
}

func (l *OrgUnitLogic) Update(id int64, req *types.OrgUnitUpdateReq) (*orgunitstore.OrgUnit, error) {
	if l.svcCtx.OrgUnits == nil {
		return nil, fmt.Errorf("org unit store unavailable")
	}
	return l.svcCtx.OrgUnits.Update(l.ctx, authx.TenantID(l.ctx), id, orgunitstore.UpdateInput{
		Name: req.Name,
		Code: req.Code,
	})
}

func (l *OrgUnitLogic) Delete(id int64) error {
	if l.svcCtx.OrgUnits == nil {
		return fmt.Errorf("org unit store unavailable")
	}
	return l.svcCtx.OrgUnits.Delete(l.ctx, authx.TenantID(l.ctx), id)
}
