package example

import (
	"context"
	"errors"
	"time"
)

// AttachmentCategory 附件分类实体
type AttachmentCategory struct {
	ID        uint
	Name      string
	Pid       uint
	Children  []*AttachmentCategory
	CreatedAt time.Time
	UpdatedAt time.Time
}

// AttachmentCategoryRepo 附件分类仓储接口
type AttachmentCategoryRepo interface {
	Create(ctx context.Context, category *AttachmentCategory) error
	Update(ctx context.Context, category *AttachmentCategory) error
	Delete(ctx context.Context, id uint) error
	FindByID(ctx context.Context, id uint) (*AttachmentCategory, error)
	FindByNameAndPid(ctx context.Context, name string, pid uint) (*AttachmentCategory, error)
	FindAll(ctx context.Context) ([]*AttachmentCategory, error)
	HasChildren(ctx context.Context, id uint) (bool, error)
}

// AttachmentCategoryUsecase 附件分类用例
type AttachmentCategoryUsecase struct {
	repo AttachmentCategoryRepo
}

// NewAttachmentCategoryUsecase 创建附件分类用例
func NewAttachmentCategoryUsecase(repo AttachmentCategoryRepo) *AttachmentCategoryUsecase {
	return &AttachmentCategoryUsecase{repo: repo}
}

// AddCategory 创建/更新分类
func (uc *AttachmentCategoryUsecase) AddCategory(ctx context.Context, category *AttachmentCategory) error {
	// 检查是否已存在相同名称的分类
	existing, _ := uc.repo.FindByNameAndPid(ctx, category.Name, category.Pid)
	if existing != nil && existing.ID != category.ID {
		return errors.New("分类名称已存在")
	}

	if category.ID > 0 {
		return uc.repo.Update(ctx, category)
	}
	return uc.repo.Create(ctx, category)
}

// DeleteCategory 删除分类
func (uc *AttachmentCategoryUsecase) DeleteCategory(ctx context.Context, id uint) error {
	hasChildren, err := uc.repo.HasChildren(ctx, id)
	if err != nil {
		return err
	}
	if hasChildren {
		return errors.New("请先删除子级")
	}
	return uc.repo.Delete(ctx, id)
}

// GetCategoryList 获取分类列表（树形）
func (uc *AttachmentCategoryUsecase) GetCategoryList(ctx context.Context) ([]*AttachmentCategory, error) {
	categories, err := uc.repo.FindAll(ctx)
	if err != nil {
		return nil, err
	}
	return uc.buildTree(categories, 0), nil
}

// buildTree 构建树形结构
func (uc *AttachmentCategoryUsecase) buildTree(categories []*AttachmentCategory, parentID uint) []*AttachmentCategory {
	var tree []*AttachmentCategory
	for _, category := range categories {
		if category.Pid == parentID {
			category.Children = uc.buildTree(categories, category.ID)
			tree = append(tree, category)
		}
	}
	return tree
}
