package example

import (
	"context"
	"time"
)

// Customer 客户实体
type Customer struct {
	ID                 uint
	CustomerName       string
	CustomerPhoneData  string
	SysUserID          uint
	SysUserAuthorityID uint
	SysUserName        string // 关联用户名
	CreatedAt          time.Time
	UpdatedAt          time.Time
}

// CustomerSearchReq 客户搜索请求
type CustomerSearchReq struct {
	Page     int
	PageSize int
}

// CustomerRepo 客户仓储接口
type CustomerRepo interface {
	Create(ctx context.Context, customer *Customer) error
	Update(ctx context.Context, customer *Customer) error
	Delete(ctx context.Context, id uint) error
	FindByID(ctx context.Context, id uint) (*Customer, error)
	List(ctx context.Context, authorityIds []uint, page, pageSize int) ([]*Customer, int64, error)
}

// DataAuthorityProvider 数据权限提供者接口
type DataAuthorityProvider interface {
	GetDataAuthorityIds(ctx context.Context, authorityId uint) ([]uint, error)
}

// SimpleDataAuthorityProvider 简单数据权限提供者（返回自身ID）
type SimpleDataAuthorityProvider struct{}

func (s *SimpleDataAuthorityProvider) GetDataAuthorityIds(ctx context.Context, authorityId uint) ([]uint, error) {
	return []uint{authorityId}, nil
}

// CustomerUsecase 客户用例
type CustomerUsecase struct {
	repo         CustomerRepo
	authProvider DataAuthorityProvider
}

// NewCustomerUsecase 创建客户用例
func NewCustomerUsecase(repo CustomerRepo, authProvider DataAuthorityProvider) *CustomerUsecase {
	return &CustomerUsecase{repo: repo, authProvider: authProvider}
}

// CreateExaCustomer 创建客户
func (uc *CustomerUsecase) CreateExaCustomer(ctx context.Context, customer *Customer) error {
	return uc.repo.Create(ctx, customer)
}

// DeleteExaCustomer 删除客户
func (uc *CustomerUsecase) DeleteExaCustomer(ctx context.Context, id uint) error {
	return uc.repo.Delete(ctx, id)
}

// UpdateExaCustomer 更新客户
func (uc *CustomerUsecase) UpdateExaCustomer(ctx context.Context, customer *Customer) error {
	return uc.repo.Update(ctx, customer)
}

// GetExaCustomer 获取客户信息
func (uc *CustomerUsecase) GetExaCustomer(ctx context.Context, id uint) (*Customer, error) {
	return uc.repo.FindByID(ctx, id)
}

// GetCustomerInfoList 分页获取客户列表
func (uc *CustomerUsecase) GetCustomerInfoList(ctx context.Context, authorityId uint, page, pageSize int) ([]*Customer, int64, error) {
	// 获取数据权限ID列表
	dataIds, err := uc.authProvider.GetDataAuthorityIds(ctx, authorityId)
	if err != nil {
		return nil, 0, err
	}

	return uc.repo.List(ctx, dataIds, page, pageSize)
}
