package models

import (
	"context"
	"time"

	"github.com/uptrace/bun"
)

type CreditCard struct {
	bun.BaseModel `bun:"table:credit_cards"`
	CreditCardID  int64     `bun:",pk,autoincrement" json:"credit_card_id" yaml:"credit_card_id"`
	UserID        int64     `json:"user_id" yaml:"user_id"`
	Title         string    `bun:"title,type:text" json:"title,omitempty" yaml:"title,omitempty"`
	Bank          string    `bun:"bank,type:text" json:"bank,omitempty" yaml:"bank,omitempty"`
	Type          string    `bun:"type,type:text" json:"type,omitempty" yaml:"type,omitempty"`
	Digits        string    `bun:"digits,type:text,unique" json:"digits,omitempty" yaml:"digits,omitempty"`
	Created       time.Time `bun:",nullzero,notnull,default:current_timestamp" json:"created" yaml:"created"`
	Updated       time.Time `json:"updated" yaml:"updated"`
}

type CreditCards []*CreditCard

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

func (*CreditCard) AfterCreateTable(ctx context.Context, query *bun.CreateTableQuery) error {
	_, err := query.DB().NewCreateIndex().Model((*CreditCard)(nil)).Index("idx_credit_card_title").Column("title").Exec(ctx)
	if err != nil {
		return err
	}
	_, err = query.DB().NewCreateIndex().Model((*CreditCard)(nil)).Index("idx_credit_card_type").Column("type").Exec(ctx)
	if err != nil {
		return err
	}
	_, err = query.DB().NewCreateIndex().Model((*CreditCard)(nil)).Index("idx_credit_card_digits").Column("digits").Exec(ctx)
	if err != nil {
		return err
	}
	return nil
}

// Add .
func (cc *CreditCard) Add(db *bun.DB, ctx context.Context) error {
	_, err := db.NewInsert().Model(cc).On("CONFLICT (digits) DO UPDATE").Set("updated = EXCLUDED.updated").Exec(ctx)
	if err != nil {
		return err
	}

	return nil
}
