package schema

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

	"entgo.io/ent"
	"entgo.io/ent/dialect"
	"entgo.io/ent/dialect/entsql"
	"entgo.io/ent/schema"
	"entgo.io/ent/schema/field"
	"github.com/jackc/pgx/v5/pgtype"
	"github.com/shopspring/decimal"
)

var shopDefaultRating = decimal.RequireFromString("5.00")

type TextArray pgtype.Array[string]

func (s *TextArray) Scan(src any) error {
	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:
		return errors.New("failed to scan text array")
	}

	trimmed := strings.Trim(strSrc, "{}")
	if len(trimmed) == 0 {
		s.Elements = []string{}
		s.Dims = nil
		s.Valid = true
		return nil
	}

	s.Elements = strings.Split(trimmed, ",")
	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
}

// Shops holds the schema definition for the Shops entity.
type Shops struct {
	ent.Schema
}

// Annotations of the Shops.
func (Shops) Annotations() []schema.Annotation {
	return []schema.Annotation{
		entsql.Annotation{
			Table: "shops",
			Checks: map[string]string{
				"chk_commission_type": "commission_type IN ('fixed', 'percentage')",
				"chk_dispatch_mode":   "dispatch_mode IN ('manual', 'auto')",
				"chk_rating_range":    "rating >= 0 AND rating <= 5",
			},
		},
	}
}

// Fields of the Shops.
func (Shops) Fields() []ent.Field {
	return []ent.Field{
		field.Int64("id").Immutable().Unique(),
		field.Int64("owner_id").Unique(),
		field.String("name").MaxLen(200),
		field.String("banner").Optional().Nillable(),
		field.String("description").Optional().Nillable(),
		field.Other("rating", decimal.Decimal{}).
			Optional().
			Default(shopDefaultRating).
			SchemaType(map[string]string{
				dialect.Postgres: "decimal(3,2)",
			}),
		field.Int("total_orders").Optional().Default(0),
		field.Int("player_count").Optional().Default(0),
		field.String("commission_type").MaxLen(20).Default("percentage"),
		field.Other("commission_value", decimal.Decimal{}).
			SchemaType(map[string]string{
				dialect.Postgres: "decimal(10,2)",
			}),
		field.Bool("allow_multi_shop").Optional().Default(false),
		field.Bool("allow_independent_orders").Optional().Default(true),
		field.String("dispatch_mode").MaxLen(20).Default("manual"),
		field.Other("announcements", TextArray{}).
			SchemaType(map[string]string{dialect.Postgres: "text[]"}).
			Optional(),
		field.JSON("template_config", map[string]any{}).Optional(),
		field.Time("created_at").Default(time.Now).Immutable(),
		field.Time("updated_at").Default(time.Now).UpdateDefault(time.Now),
	}
}

// Edges of the Shops.
func (Shops) Edges() []ent.Edge {
	return nil
}
