package models

import (
	"context"
	"encoding/json"
	"strings"
	"time"

	"github.com/uptrace/bun"
)

type Receipt struct {
	bun.BaseModel `bun:"table:receipts"`
	ReceiptID     int64       `bun:",pk,autoincrement" json:"receipt_id" yaml:"receipt_id"`
	UserID        int64       `json:"user_id" yaml:"user_id"`
	GroupID       int64       `json:"group_id" yaml:"group_id"`
	MerchantID    int64       `json:"merchant_id" yaml:"merchant_id"`
	CreditCardID  int64       `json:"credit_card_id" yaml:"credit_card_id"`
	CreditCard    *CreditCard `bun:"credit_card,rel:belongs-to,join:credit_card_id=credit_card_id" json:"credit_card,omitempty" yaml:"credit_card,omitempty"`
	Merchant      *Merchant   `bun:"merchant,rel:belongs-to,join:merchant_id=merchant_id" json:"merchant" yaml:"merchant"`
	URL           string      `bun:"url" json:"url" yaml:"url"`
	Type          string      `bun:"type" json:"type" yaml:"type"`
	Category      string      `bun:"category" json:"category" yaml:"category"`
	Items         Items       `bun:"rel:has-many,join:receipt_id=item_id" json:"items" yaml:"items"`
	Tax           float64     `bun:"tax" json:"tax,omitempty" yaml:"tax,omitempty"`
	CCFee         float64     `bun:"cc_fee" json:"cc_fee,omitempty" yaml:"cc_fee,omitempty"`
	Tips          float64     `bun:"tips" json:"tips,omitempty" yaml:"tips,omitempty"`
	Total         float64     `bun:"total" json:"total" yaml:"total"`
	PaidWith      string      `bun:"paid_with" json:"paid_with" yaml:"paid_with"`
	PaidAt        string      `bun:"paid_at" json:"paid_at" yaml:"paid_at"`
	Created       time.Time   `bun:",nullzero,notnull,default:current_timestamp" json:"created" yaml:"created"`
	Updated       time.Time   `json:"updated" yaml:"updated"`
}

type Receipts []*Receipt

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

// AfterCreateTable .
func (*Receipt) AfterCreateTable(ctx context.Context, query *bun.CreateTableQuery) error {
	_, err := query.DB().NewCreateIndex().Model((*Receipt)(nil)).Index("idx_receipts_category").Column("category").Exec(ctx)
	if err != nil {
		return err
	}
	return nil
}

// NewReceipt .
func NewReceipt(j []byte) (*Receipt, error) {
	var r *Receipt
	if err := json.Unmarshal([]byte(j), &r); err != nil {
		panic(err)
	}
	return r, nil
}

// Add .
func (r *Receipt) Add(db *bun.DB, ctx context.Context) error {

	err := r.Merchant.Add(db, ctx)
	if err != nil {
		return err
	}

	err = r.CreditCard.Add(db, ctx)
	if err != nil {
		return err
	}

	_, err = db.NewInsert().Model(r).Exec(ctx)
	if err != nil {
		return err
	}

	if len(r.Items) > 0 {
		for _, item := range r.Items {
			item.ReceiptID = r.ReceiptID
			item.Title = strings.Title(strings.ToLower(item.Title))
		}
		err = r.Items.Add(db, ctx)
		if err != nil {
			return err
		}
	}

	return nil
}

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

// Remove .
func (r *Receipt) Remove(db *bun.DB, ctx context.Context) error {
	err := r.Items.Remove(db, ctx)
	if err != nil {
		return err
	}
	_, err = db.NewDelete().Where("receipt_id = ?", r.ReceiptID).Exec(ctx)
	if err != nil {
		return err
	}
	return nil
}

// Select .
func (r *Receipt) Select(db *bun.DB, ctx context.Context, id int64) error {
	err := db.NewSelect().Model(r).Where("receipt_id = ?", id).Scan(ctx)
	if err != nil {
		return err
	}

	return nil
}
