package repository

import (
	"context"
	v1 "github.com/go-nunu/nunu-layout-advanced/api/v1"
	"math"
	"strings"

	"github.com/go-nunu/nunu-layout-advanced/internal/model"
)

type GateWayGroupIpRepository interface {
	GetGateWayGroupIp(ctx context.Context, id int64) (*model.GateWayGroupIp, error)
	AddGateWayGroupIp(ctx context.Context, req *model.GateWayGroupIp) error
	EditGateWayGroupIp(ctx context.Context, req *model.GateWayGroupIp) error
	DeleteGateWayGroupIp(ctx context.Context, req *model.GateWayGroupIp) error
	GetGateWayGroupIpByGatewayGroupId(ctx context.Context, gatewayGroupId int) ([]model.GateWayGroupIp, error)
	GetGateWayGroupFirstIpByGatewayGroupId(ctx context.Context, gatewayGroupId int) (string, error)
	GetGateWayGroupAllIpByGatewayGroupId(ctx context.Context, gatewayGroupId int) ([]string, error)
	GetGatewayGroupIpList(ctx context.Context,req v1.SearchGatewayGroupIpParams) (*v1.PaginatedResponse[model.GateWayGroupIp], error)
}

func NewGateWayGroupIpRepository(
	repository *Repository,
) GateWayGroupIpRepository {
	return &gateWayGroupIpRepository{
		Repository: repository,
	}
}

type gateWayGroupIpRepository struct {
	*Repository
}

func (r *gateWayGroupIpRepository) GetGateWayGroupIp(ctx context.Context, id int64) (*model.GateWayGroupIp, error) {
	var res model.GateWayGroupIp
	if err := r.DB(ctx).Where("id = ?", id).First(&res).Error; err != nil {
		return nil, err
	}
	return &res, nil
}

func (r *gateWayGroupIpRepository) AddGateWayGroupIp(ctx context.Context, req *model.GateWayGroupIp) error {
	if err := r.DB(ctx).Create(req).Error; err != nil {
		return err
	}
	return nil
}

func (r *gateWayGroupIpRepository) EditGateWayGroupIp(ctx context.Context, req *model.GateWayGroupIp) error {
	if err := r.DB(ctx).Model(&model.GateWayGroupIp{}).Where("id = ?", req.Id).Updates(req).Error; err != nil {
		return err
	}
	return nil

}

func (r *gateWayGroupIpRepository) DeleteGateWayGroupIp(ctx context.Context, req *model.GateWayGroupIp) error {
	if err := r.DB(ctx).Model(&model.GateWayGroupIp{}).Where("id = ?", req.Id).Delete(req).Error; err != nil {
		return err
	}
	return nil

}

func (r *gateWayGroupIpRepository) GetGateWayGroupIpByGatewayGroupId(ctx context.Context, gatewayGroupId int) ([]model.GateWayGroupIp, error) {
	var res []model.GateWayGroupIp
	if err := r.DB(ctx).Model(&model.GateWayGroupIp{}).Where("gateway_group_id = ?", gatewayGroupId).Find(&res).Error; err != nil {
		return nil, err
	}
	return res, nil

}

func (r *gateWayGroupIpRepository) GetGateWayGroupFirstIpByGatewayGroupId(ctx context.Context, gatewayGroupId int) (string, error) {
	var res string
	if err := r.DB(ctx).Model(&model.GateWayGroupIp{}).Where("gateway_group_id = ?", gatewayGroupId).Select("ip").Order("id asc").First(&res).Error; err != nil {
		return "", err
	}
	return res, nil
}

func (r *gateWayGroupIpRepository) GetGateWayGroupAllIpByGatewayGroupId(ctx context.Context, gatewayGroupId int) ([]string, error) {
	var res []string
	if err := r.DB(ctx).Model(&model.GateWayGroupIp{}).Where("gateway_group_id = ?", gatewayGroupId).Select("ip").Find(&res).Error; err != nil {
		return nil, err
	}
	return res, nil
}

func (r *gateWayGroupIpRepository) GetGatewayGroupIpList(ctx context.Context,req v1.SearchGatewayGroupIpParams) (*v1.PaginatedResponse[model.GateWayGroupIp], error) {
	var res []model.GateWayGroupIp
	var total int64

	query := r.Db.WithContext(ctx).Model(&model.GateWayGroupIp{})
	if  req.Ip != "" {
		trimmedName := strings.TrimSpace(req.Ip)
		// 使用 LIKE 进行模糊匹配
		query = query.Where("ip LIKE CONCAT('%', ?, '%')", trimmedName)
	}

	// 如果 RuleId 被提供了
	if req.GatewayGroupId != 0 {
		query = query.Where("gateway_group_id = ?", req.GatewayGroupId)
	}

	// 如果 Operator 被提供了
	if req.Operator != 0 {
		query = query.Where("operator = ?", req.Operator)
	}

	if req.Column != "" {
		if req.Column == "createTime" {
			query = query.Order("created_at" + " " + req.Order)
		}
	}

	if err := query.Count(&total).Error; err != nil {
		// 如果连计数都失败了，直接返回错误
		return nil, err
	}


	page := req.Current
	pageSize := req.PageSize

	if page <= 0 {
		page = 1
	}

	if pageSize <= 0 {
		pageSize = 10 // 默认每页 10 条
	} else if pageSize > 100 {
		pageSize = 100 // 每页最多 100 条
	}

	// 计算 offset (偏移量)
	// 例如，第 1 页，offset = (1-1)*10 = 0 (从第0条开始)
	// 第 2 页，offset = (2-1)*10 = 10 (从第10条开始)
	offset := (page - 1) * pageSize
	// 3. 执行最终的查询
	// 在所有条件都添加完毕后，再执行 .Find()
	result := query.Offset(offset).Limit(pageSize).Find(&res)
	if result.Error != nil {
		// 这里的错误可能是数据库连接问题等，而不是“未找到记录”
		return nil, result.Error
	}
	return &v1.PaginatedResponse[model.GateWayGroupIp]{
		Records: res,
		Page: page,
		PageSize: pageSize,
		Total: total,
		TotalPages: int(math.Ceil(float64(total) / float64(pageSize))),

	}, nil
}