package types

import (
	"database/sql/driver"
	"errors"
	"strings"

	"github.com/jackc/pgx/v5/pgtype"
	"github.com/zeromicro/go-zero/core/logx"
)

type TextArray pgtype.Array[string]

func (s *TextArray) Scan(src any) error {
	logx.Infof("scan src=%+v", src)
	if src == nil {
		s.Elements = []string{}
		s.Dims = nil
		s.Valid = true
		return nil
	}

	var strSrc string
	switch v := src.(type) {
	case string:
		strSrc = v
	case []byte:
		strSrc = string(v)
	default:
		logx.Errorf("src=%+v, failed to assert src as string or []byte", src)
		return errors.New("failed to scan src")
	}

	trimmed := strings.Trim(strSrc, "{}")
	result := strings.Split(trimmed, ",")
	logx.Debugf("split result=%+v", result)
	if len(trimmed) == 0 {
		result = []string{}
	}
	s.Elements = result
	s.Dims = nil
	s.Valid = true
	return nil
}

func (s TextArray) Value() (driver.Value, error) {
	if s.Elements == nil {
		return []string{}, nil
	}
	return s.Elements, nil
}
