package base

import (
	"database/sql/driver"
	"errors"
	"fmt"
	"strings"
	"time"
)

type ID uint64

type Base struct {
	ID        ID        `gorm:"primary_key;not null"`
	CreatedAt time.Time `gorm:"created_at;type:TIMESTAMP;not null;<-:create"` // create and read only
}

type Updatable struct {
	Base
	UpdatedAt *time.Time `gorm:"updated_at;type:TIMESTAMP"`
}

func (id ID) Uint64() uint64 {
	return uint64(id)
}

func (u Base) GetID() ID {
	return u.ID
}

type Set []string

func (s *Set) Scan(value any) (err error) {
	var str string
	switch v := value.(type) {
	case []byte:
		str = string(v)
	case string:
		str = v
	default:
		return errors.New(fmt.Sprint("Failed to parse Set:", value))
	}

	*s = strings.Split(str, ",")
	return
}

func (s Set) Value() (driver.Value, error) {
	return strings.Join(s, ","), nil
}
