package logic

import (
	"encoding/json"
	"errors"

	"juwan-backend/app/dispute/rpc/internal/models"
	"juwan-backend/app/dispute/rpc/pb"
	"juwan-backend/pkg/types"

	"github.com/jackc/pgx/v5/pgtype"
)

func toTextArray(s []string) types.TextArray {
	if len(s) == 0 {
		return types.TextArray{Valid: true}
	}
	return types.TextArray{
		Elements: s,
		Dims:     []pgtype.ArrayDimension{{Length: int32(len(s)), LowerBound: 1}},
		Valid:    true,
	}
}

func parseJSONMap(v string) (map[string]any, error) {
	if v == "" {
		return map[string]any{}, nil
	}
	var result map[string]any
	if err := json.Unmarshal([]byte(v), &result); err != nil {
		return nil, errors.New("invalid json value")
	}
	if result == nil {
		return map[string]any{}, nil
	}
	return result, nil
}

func entDisputeToPb(d *models.Disputes) *pb.Disputes {
	out := &pb.Disputes{
		Id:                 d.ID,
		OrderId:            d.OrderID,
		InitiatorId:        d.InitiatorID,
		InitiatorName:      d.InitiatorName,
		RespondentId:       d.RespondentID,
		Reason:             d.Reason,
		Evidence:           d.Evidence.Elements,
		Status:             d.Status,
		RespondentEvidence: d.RespondentEvidence.Elements,
		CreatedAt:          d.CreatedAt.Unix(),
		UpdatedAt:          d.UpdatedAt.Unix(),
	}
	if d.Result != nil {
		out.Result = *d.Result
	}
	if d.RespondentReason != nil {
		out.RespondentReason = *d.RespondentReason
	}
	if d.AppealReason != nil {
		out.AppealReason = *d.AppealReason
	}
	if d.AppealedAt != nil {
		out.AppealedAt = d.AppealedAt.Unix()
	}
	if d.ResolvedBy != nil {
		out.ResolvedBy = *d.ResolvedBy
	}
	if d.ResolvedAt != nil {
		out.ResolvedAt = d.ResolvedAt.Unix()
	}
	return out
}

func entDisputeTimelineToPb(t *models.DisputeTimeline) *pb.DisputeTimeline {
	details := "{}"
	if t.Details != nil {
		if b, err := json.Marshal(t.Details); err == nil {
			details = string(b)
		}
	}
	return &pb.DisputeTimeline{
		Id:        t.ID,
		DisputeId: t.DisputeID,
		EventType: t.EventType,
		ActorId:   t.ActorID,
		ActorName: t.ActorName,
		Details:   details,
		CreatedAt: t.CreatedAt.Unix(),
	}
}
