package models

import (
	"context"
	"time"

	"github.com/uptrace/bun"
)

type User struct {
	bun.BaseModel    `bun:"table:users"`
	UserID           int64       `bun:",pk,autoincrement" json:"user_id" yaml:"user_id"`
	GroupID          int64       `json:"-" yaml:"-"`
	Name             string      `bun:"name,type:text,unique" json:"name" yaml:"name"`
	Email            string      `bun:"email,type:text" json:"email,omitempty" yaml:"email,omitempty"`
	TelegramID       int64       `bun:"telegram_id,type:int,unique" json:"telegram_id" yaml:"telegram_id"`
	TelegramUsername string      `bun:"telegram_username,type:text,unique" json:"telegram_username" yaml:"telegram_username"`
	Receipts         Receipts    `bun:"rel:has-many,join:user_id=receipt_id"`
	CreditCards      CreditCards `bun:"rel:has-many,join:user_id=credit_card_id"`
	Created          time.Time   `bun:",nullzero,notnull,default:current_timestamp" json:"created" yaml:"created"`
	Updated          time.Time   `json:"updated" yaml:"updated"`
}

type Users []*User

var _ bun.AfterCreateTableHook = (*User)(nil)

func (*User) AfterCreateTable(ctx context.Context, query *bun.CreateTableQuery) error {
	_, err := query.DB().NewCreateIndex().Model((*User)(nil)).Index("idx_users_name").Column("name").Exec(ctx)
	if err != nil {
		return err
	}
	_, err = query.DB().NewCreateIndex().Model((*User)(nil)).Index("idx_users_telegram_id").Column("telegram_id").Exec(ctx)
	if err != nil {
		return err
	}
	_, err = query.DB().NewCreateIndex().Model((*User)(nil)).Index("idx_users_telegram_username").Column("telegram_username").Exec(ctx)
	if err != nil {
		return err
	}
	return nil
}

func NewUser(j []byte) (*User, error) {
	u := &User{}
	// u := &User{Name: fmt.Sprintf("%s %s", c.Sender().FirstName, c.Sender().LastName), TelegramID: c.Sender().ID, TelegramUsername: c.Sender().Username}
	return u, nil
}

func (u *User) Add(db *bun.DB, ctx context.Context) error {
	_, err := db.NewInsert().Model(u).Exec(ctx)
	if err != nil {
		return err
	}
	return nil
}

func (u *User) Update(db *bun.DB, ctx context.Context) error {
	_, err := db.NewUpdate().Model(u).WherePK().Exec(ctx)
	if err != nil {
		return err
	}

	return nil
}

func (u *User) Remove(db *bun.DB, ctx context.Context) error {
	_, err := db.NewDelete().Model(u).WherePK().Exec(ctx)
	if err != nil {
		return err
	}

	return nil
}

func UserExists(db *bun.DB, ctx context.Context, tid int64) bool {
	exists, err := db.NewSelect().Model((*User)(nil)).Where("telegram_id = ?", tid).Exists(ctx)
	if err != nil {
		panic(err)
	}

	return exists
}
