package service

import (
	"database/sql"
	"encoding/json"
	"fmt"
	"log"

	"github.com/seifghazi/claude-code-monitor/internal/model"
)

func unmarshalStoredRequestFields(logger *log.Logger, req *model.RequestLog, headersJSON, bodyJSON string, promptGradeJSON, responseJSON sql.NullString) error {
	if err := json.Unmarshal([]byte(headersJSON), &req.Headers); err != nil {
		return fmt.Errorf("failed to unmarshal headers: %w", err)
	}

	var body interface{}
	if err := json.Unmarshal([]byte(bodyJSON), &body); err != nil {
		return fmt.Errorf("failed to unmarshal body: %w", err)
	}
	req.Body = body

	if promptGradeJSON.Valid {
		var grade model.PromptGrade
		if err := json.Unmarshal([]byte(promptGradeJSON.String), &grade); err != nil {
			if logger != nil {
				logger.Printf("Warning: failed to unmarshal prompt grade: %v", err)
			}
		} else {
			req.PromptGrade = &grade
		}
	}

	if responseJSON.Valid {
		var resp model.ResponseLog
		if err := json.Unmarshal([]byte(responseJSON.String), &resp); err != nil {
			if logger != nil {
				logger.Printf("Warning: failed to unmarshal response: %v", err)
			}
		} else {
			req.Response = &resp
		}
	}

	return nil
}
