package sqlite

import (
	"context"
	"fmt"
	"strings"
)

type ProbeResult struct {
	ID          int64
	BatchItemID int64
	ProbeType   string
	Status      string
	SummaryJSON string
}

type ProbeResultsRepo struct {
	db execQuerier
}

func newProbeResultsRepo(db execQuerier) *ProbeResultsRepo {
	return &ProbeResultsRepo{db: db}
}

func (r *ProbeResultsRepo) Create(ctx context.Context, probe ProbeResult) (int64, error) {
	probeType := strings.TrimSpace(probe.ProbeType)
	status := strings.TrimSpace(probe.Status)
	summaryJSON := strings.TrimSpace(probe.SummaryJSON)
	if summaryJSON == "" {
		summaryJSON = "{}"
	}

	switch {
	case probe.BatchItemID <= 0:
		return 0, fmt.Errorf("batch_item_id is required")
	case probeType == "":
		return 0, fmt.Errorf("probe_type is required")
	case status == "":
		return 0, fmt.Errorf("status is required")
	}

	result, err := r.db.ExecContext(ctx, `INSERT INTO probe_results (batch_item_id, probe_type, status, summary_json) VALUES (?, ?, ?, ?)`, probe.BatchItemID, probeType, status, summaryJSON)
	if err != nil {
		return 0, fmt.Errorf("insert probe result: %w", err)
	}

	id, err := result.LastInsertId()
	if err != nil {
		return 0, fmt.Errorf("read inserted probe result id: %w", err)
	}
	return id, nil
}

func (r *ProbeResultsRepo) GetByBatchItemID(ctx context.Context, batchItemID int64) ([]ProbeResult, error) {
	if batchItemID <= 0 {
		return nil, fmt.Errorf("batch_item_id is required")
	}

	rows, err := r.db.QueryContext(ctx, `SELECT id, batch_item_id, probe_type, status, summary_json FROM probe_results WHERE batch_item_id = ? ORDER BY id`, batchItemID)
	if err != nil {
		return nil, fmt.Errorf("query probe results: %w", err)
	}
	defer rows.Close()

	probes := make([]ProbeResult, 0)
	for rows.Next() {
		var probe ProbeResult
		if err := rows.Scan(&probe.ID, &probe.BatchItemID, &probe.ProbeType, &probe.Status, &probe.SummaryJSON); err != nil {
			return nil, fmt.Errorf("scan probe result: %w", err)
		}
		probes = append(probes, probe)
	}
	if err := rows.Err(); err != nil {
		return nil, fmt.Errorf("iterate probe results: %w", err)
	}
	return probes, nil
}
