package example

import (
	"context"

	"kra/internal/biz/example"
	"kra/internal/data/model"
	"kra/internal/data/query"

	"gorm.io/gorm"
)

type attachmentCategoryRepo struct {
	db *gorm.DB
}

// NewAttachmentCategoryRepo 创建附件分类仓储
func NewAttachmentCategoryRepo(db *gorm.DB) example.AttachmentCategoryRepo {
	return &attachmentCategoryRepo{db: db}
}

func (r *attachmentCategoryRepo) Create(ctx context.Context, category *example.AttachmentCategory) error {
	m := &model.ExaAttachmentCategory{
		Name: category.Name,
		Pid:  int64(category.Pid),
	}
	return r.db.WithContext(ctx).Create(m).Error
}

func (r *attachmentCategoryRepo) Update(ctx context.Context, category *example.AttachmentCategory) error {
	return r.db.WithContext(ctx).Model(&model.ExaAttachmentCategory{}).
		Where("id = ?", category.ID).
		Updates(map[string]any{
			"name": category.Name,
			"pid":  category.Pid,
		}).Error
}

func (r *attachmentCategoryRepo) Delete(ctx context.Context, id uint) error {
	return r.db.WithContext(ctx).Unscoped().
		Where("id = ?", id).
		Delete(&model.ExaAttachmentCategory{}).Error
}

func (r *attachmentCategoryRepo) FindByID(ctx context.Context, id uint) (*example.AttachmentCategory, error) {
	c := query.ExaAttachmentCategory
	m, err := c.WithContext(ctx).Where(c.ID.Eq(int64(id))).First()
	if err != nil {
		return nil, err
	}
	return toCategoryBiz(m), nil
}

func (r *attachmentCategoryRepo) FindByNameAndPid(ctx context.Context, name string, pid uint) (*example.AttachmentCategory, error) {
	c := query.ExaAttachmentCategory
	m, err := c.WithContext(ctx).Where(c.Name.Eq(name), c.Pid.Eq(int64(pid))).First()
	if err != nil {
		return nil, err
	}
	return toCategoryBiz(m), nil
}

func (r *attachmentCategoryRepo) FindAll(ctx context.Context) ([]*example.AttachmentCategory, error) {
	c := query.ExaAttachmentCategory
	list, err := c.WithContext(ctx).Find()
	if err != nil {
		return nil, err
	}

	result := make([]*example.AttachmentCategory, len(list))
	for i, m := range list {
		result[i] = toCategoryBiz(m)
	}
	return result, nil
}

func (r *attachmentCategoryRepo) HasChildren(ctx context.Context, id uint) (bool, error) {
	c := query.ExaAttachmentCategory
	count, err := c.WithContext(ctx).Where(c.Pid.Eq(int64(id))).Count()
	return count > 0, err
}

// 转换函数
func toCategoryBiz(m *model.ExaAttachmentCategory) *example.AttachmentCategory {
	return &example.AttachmentCategory{
		ID:        uint(m.ID),
		Name:      m.Name,
		Pid:       uint(m.Pid),
		CreatedAt: m.CreatedAt,
		UpdatedAt: m.UpdatedAt,
	}
}
