// Generated by testgen: rewritten every time tests are generated, do not edit.
// testgen (@xylentis/testgen), Copyright (C) 2026 Xylentis. Licensed under AGPL-3.0-only with an additional
// permission: as part of tests generated by testgen, this file may be used, modified and distributed under
// terms of your choice (see NOTICE in @xylentis/testgen).

package e2e

import (
	"bytes"
	"encoding/csv"
	"os"
	"strings"
	"testing"
)

// readTestgenCSV returns the rows of the CSV data file of a data-driven test, with the given columns.
// The file is UTF-8, with or without a BOM, separated by commas or semicolons (as Excel saves it in
// some languages), and its first line names the columns; other columns are ignored, blank lines skipped.
func readTestgenCSV(t *testing.T, file string, columns ...string) []map[string]string {
	t.Helper()
	data, err := os.ReadFile(file)
	if err != nil {
		t.Fatalf("testgen: %v", err)
	}
	data = bytes.TrimPrefix(data, []byte("\uFEFF"))
	reader := csv.NewReader(bytes.NewReader(data))
	reader.FieldsPerRecord = -1
	if firstLine, _, _ := strings.Cut(string(data), "\n"); !strings.Contains(firstLine, ",") && strings.Contains(firstLine, ";") {
		reader.Comma = ';'
	}
	records, err := reader.ReadAll()
	if err != nil {
		t.Fatalf("testgen: data file %s: %v", file, err)
	}
	if len(records) == 0 {
		t.Fatalf("testgen: data file %s is empty", file)
	}
	header := map[string]int{}
	for i, name := range records[0] {
		header[strings.TrimSpace(name)] = i
	}
	for _, column := range columns {
		if _, ok := header[column]; !ok {
			t.Fatalf("testgen: data file %s has no column %q (it has %s)", file, column, strings.Join(records[0], ", "))
		}
	}
	var rows []map[string]string
	for _, record := range records[1:] {
		if strings.TrimSpace(strings.Join(record, "")) == "" {
			continue
		}
		row := map[string]string{}
		for _, column := range columns {
			if i := header[column]; i < len(record) {
				row[column] = record[i]
			}
		}
		rows = append(rows, row)
	}
	if len(rows) == 0 {
		t.Fatalf("testgen: data file %s has no data rows", file)
	}
	return rows
}
