package database

import (
	"fmt"

	"github.com/jackc/pgio"
	"github.com/jackc/pgtype"
)

const NewInvoiceProductTypeName = "new_invoice_product"

type NewInvoiceProduct struct {
	ProductId   int
	Name        string
	Description string
	Price       string
	Quantity    int
	Discount    float64
	Taxes       []int
}

func (src NewInvoiceProduct) EncodeBinary(ci *pgtype.ConnInfo, dst []byte) ([]byte, error) {
	typeName := NewInvoiceProductTypeName
	dt, ok := ci.DataTypeForName(typeName)
	if !ok {
		return nil, fmt.Errorf("unable to find oid for type name %v", typeName)
	}
	var productId interface{}
	if src.ProductId > 0 {
		productId = src.ProductId
	}
	values := []interface{}{
		productId,
		src.Name,
		src.Description,
		src.Price,
		src.Quantity,
		src.Discount,
		src.Taxes,
	}
	ct := pgtype.NewValue(dt.Value).(*pgtype.CompositeType)
	if err := ct.Set(values); err != nil {
		return nil, err
	}
	return ct.EncodeBinary(ci, dst)
}

type NewInvoiceProductArray []*NewInvoiceProduct

func (src NewInvoiceProductArray) EncodeBinary(ci *pgtype.ConnInfo, buf []byte) ([]byte, error) {
	typeName := NewInvoiceProductTypeName
	dt, ok := ci.DataTypeForName(typeName)
	if !ok {
		return nil, fmt.Errorf("unable to find oid for type name %v", typeName)
	}

	arrayHeader := pgtype.ArrayHeader{
		ElementOID: int32(dt.OID),
		Dimensions: []pgtype.ArrayDimension{{Length: int32(len(src)), LowerBound: 1}},
	}
	buf = arrayHeader.EncodeBinary(ci, buf)
	for _, product := range src {
		sp := len(buf)
		buf = pgio.AppendInt32(buf, -1)

		elemBuf, err := product.EncodeBinary(ci, buf)
		if err != nil {
			return nil, err
		}
		if elemBuf != nil {
			buf = elemBuf
			pgio.SetInt32(buf[sp:], int32(len(buf[sp:])-4))
		}
	}
	return buf, nil
}
