package database

import (
	"fmt"

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

const EditedInvoiceProductTypeName = "edited_invoice_product"

type EditedInvoiceProduct struct {
	*NewInvoiceProduct
	InvoiceProductId int
}

func (src EditedInvoiceProduct) EncodeBinary(ci *pgtype.ConnInfo, dst []byte) ([]byte, error) {
	typeName := EditedInvoiceProductTypeName
	dt, ok := ci.DataTypeForName(typeName)
	if !ok {
		return nil, fmt.Errorf("unable to find oid for type name %v", typeName)
	}
	var invoiceProductId interface{}
	if src.InvoiceProductId > 0 {
		invoiceProductId = src.InvoiceProductId
	}
	var productId interface{}
	if src.ProductId > 0 {
		productId = src.ProductId
	}
	values := []interface{}{
		invoiceProductId,
		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 EditedInvoiceProductArray []*EditedInvoiceProduct

func (src EditedInvoiceProductArray) EncodeBinary(ci *pgtype.ConnInfo, buf []byte) ([]byte, error) {
	typeName := EditedInvoiceProductTypeName
	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
}
