package dispute

import (
	"encoding/json"

	"hfb_sys/backend/internal/model"

	"gorm.io/datatypes"
)

type disputeRow struct {
	model.Dispute
	OrderNo          string
	OrderStatus      string
	HandoffStatus    string
	SettlementStatus string
	ListingNo        string
	Title            string
	OwnerID          uint64
	RenterID         uint64
	OwnerPhone       string
	RenterPhone      string
}

func (row disputeRow) toDTO() DisputeDTO {
	return DisputeDTO{
		ID:                       row.ID,
		OrderID:                  row.OrderID,
		OrderNo:                  row.OrderNo,
		OrderStatus:              row.OrderStatus,
		HandoffStatus:            row.HandoffStatus,
		SettlementStatus:         row.SettlementStatus,
		ListingNo:                row.ListingNo,
		Title:                    row.Title,
		OwnerID:                  row.OwnerID,
		RenterID:                 row.RenterID,
		OwnerPhone:               row.OwnerPhone,
		RenterPhone:              row.RenterPhone,
		InitiatorID:              row.InitiatorID,
		TargetUserID:             row.TargetUserID,
		Type:                     row.Type,
		Status:                   row.Status,
		Description:              row.Description,
		EvidenceURLS:             row.EvidenceURLS,
		PreviousOrderStatus:      row.PreviousOrderStatus,
		PreviousHandoffStatus:    row.PreviousHandoffStatus,
		PreviousSettlementStatus: row.PreviousSettlementStatus,
		CheckoutID:               row.CheckoutID,
		PreviousCheckoutStatus:   row.PreviousCheckoutStatus,
		ArbitrationResult:        row.ArbitrationResult,
		ArbitrationRemark:        row.ArbitrationRemark,
		HandledBy:                row.HandledBy,
		HandledAt:                row.HandledAt,
		CreatedAt:                row.CreatedAt,
		UpdatedAt:                row.UpdatedAt,
	}
}

func toDTOs(rows []disputeRow) []DisputeDTO {
	items := make([]DisputeDTO, 0, len(rows))
	for _, row := range rows {
		items = append(items, row.toDTO())
	}
	return items
}

func marshalEvidence(urls []string) (datatypes.JSON, error) {
	if len(urls) == 0 {
		return datatypes.JSON([]byte("[]")), nil
	}
	raw, err := json.Marshal(urls)
	return datatypes.JSON(raw), err
}
