package csvimporter

import (
	"context"
	"fmt"
	"strconv"
	"strings"

	"catalogue.midpdsa.com/src/db/catalogue"
	"github.com/jackc/pgx/v5/pgtype"
)

func (imp *Importer) ImportPagidBrake(filename string) (ImportResult, error) {
	result := ImportResult{Table: "brake_brand_specs"}

	records, err := imp.readCSVSeparator(filename, '|')
	if err != nil {
		return result, fmt.Errorf("failed to read CSV: %w", err)
	}
	if len(records) < 2 {
		return result, fmt.Errorf("no data rows in CSV")
	}

	ctx := context.Background()

	vehicleTypeID, err := imp.findOrCreateVehicleType(ctx, "Ligero")
	if err != nil {
		return result, fmt.Errorf("failed to get vehicle type: %w", err)
	}

	headerMap := make(map[string]int)
	for idx, col := range records[0] {
		headerMap[normalizeHeaderKey(col)] = idx
	}

	get := func(row []string, key string) string {
		idx, ok := headerMap[normalizeHeaderKey(key)]
		if !ok || idx >= len(row) {
			return ""
		}
		return row[idx]
	}

	var errorRows []ErrorRow

	for i, row := range records[1:] {
		rowNum := i + 2
		brand := get(row, "brand")
		if brand == "" {
			brand = "Hella-Pagid"
		}
		partNumber := get(row, "partnumber")
		product := get(row, "product")
		position := get(row, "position")
		fmsi := get(row, "fmsi")
		aplicacion := get(row, "aplicacion")

		if partNumber == "" || partNumber == "MISSING" {
			result.Errors++
			errorRows = append(errorRows, ErrorRow{Row: row, Error: "Missing part number", RowNum: rowNum})
			continue
		}

		vehicles := parseGrobbFritecApplications(aplicacion)
		if len(vehicles) == 0 {
			result.Errors++
			errorRows = append(errorRows, ErrorRow{Row: row, Error: "Unable to parse any vehicle from aplicacion", RowNum: rowNum})
			continue
		}

		brakeBrandID, err := imp.findOrCreateBrakeBrand(ctx, brand)
		if err != nil {
			result.Errors++
			errorRows = append(errorRows, ErrorRow{Row: row, Error: fmt.Sprintf("failed to get brake brand: %v", err), RowNum: rowNum})
			continue
		}

		pos := imp.parsePosition(position)

		for _, v := range vehicles {
			make := v.Make
			model := v.Model
			if make == "" || make == "MISSING" || model == "" || model == "MISSING" {
				result.Errors++
				errorRows = append(errorRows, ErrorRow{Row: row, Error: fmt.Sprintf("Missing make/model for vehicle (%q/%q)", make, model), RowNum: rowNum})
				continue
			}
			modelYearID, err := imp.findOrCreateVehicleModelYear(ctx, make, model, vehicleTypeID)
			if err != nil {
				result.Errors++
				errorRows = append(errorRows, ErrorRow{Row: row, Error: fmt.Sprintf("Failed to find/create vehicle: %v", err), RowNum: rowNum})
				continue
			}
			yearFrom := 0
			yearTo := 0
			if v.Year != "" {
				yearFrom, _ = strconv.Atoi(v.Year)
				yearTo = yearFrom
			} else if v.YearRange != "" {
				pts := strings.FieldsFunc(v.YearRange, func(r rune) bool { return r == ',' || r == '-' })
				if len(pts) == 2 {
					yearFrom, _ = strconv.Atoi(strings.TrimSpace(pts[0]))
					yearTo, _ = strconv.Atoi(strings.TrimSpace(pts[1]))
				}
			}
			yearsStr := ""
			yearsRangeStr := ""
			if yearFrom > 0 {
				if yearTo > 0 && yearTo != yearFrom {
					yearsRangeStr = fmt.Sprintf("%d-%d", yearFrom, yearTo)
				} else {
					yearsStr = fmt.Sprintf("%d", yearFrom)
				}
			}
			if err := imp.insertBrakeBrandSpec(ctx, catalogue.CreateBrakeBrandSpecParams{
				PartNumber:             pgtype.Text{String: partNumber, Valid: true},
				Product:                pgtype.Text{String: product, Valid: product != ""},
				Serie:                  pgtype.Text{},
				Tier:                   pgtype.Text{},
				Quantity:               pgtype.Int4{Int32: 1, Valid: true},
				Position:               pgtype.Text{String: pos, Valid: pos != ""},
				Fmsi:                   pgtype.Text{String: fmsi, Valid: fmsi != "" && fmsi != "MISSING"},
				IncludesHardware:       pgtype.Text{String: "No", Valid: true},
				ImageProduct:           pgtype.Text{},
				VehicleAttrs:           pgtype.Text{String: aplicacion, Valid: aplicacion != ""},
				ImageProductDimentions: pgtype.Text{},
				TechnicalSheet:         pgtype.Text{},
				FkIdVehicleModelYear:   pgtype.Int4{Int32: modelYearID, Valid: true},
				FkIdBrakeBrand:         pgtype.Int4{Int32: brakeBrandID, Valid: true},
				Years:                  pgtype.Text{String: yearsStr, Valid: yearsStr != ""},
				YearsRange:             pgtype.Text{String: yearsRangeStr, Valid: yearsRangeStr != ""},
			}, &result); err != nil {
				result.Errors++
				errorRows = append(errorRows, ErrorRow{Row: row, Error: fmt.Sprintf("Database insert failed: %v", err), RowNum: rowNum})
				continue
			}
		}

		if i%100 == 0 {
			fmt.Printf("  Pagid Brake: %d rows processed\n", i)
		}
	}

	if len(errorRows) > 0 {
		err = imp.writeErrorCSV("pagid_brake_errors.csv", records[0], errorRows)
		if err != nil {
			fmt.Printf("  Warning: failed to write error CSV: %v\n", err)
		}
	}

	return result, nil
}
