package csvimporter

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

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

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

	records, err := imp.readCSV(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)
	}

	brakeBrandID, err := imp.findOrCreateBrakeBrand(ctx, "Wagner")
	if err != nil {
		return result, fmt.Errorf("failed to get brake brand: %w", err)
	}

	header := records[0]
	var errorRows []ErrorRow

	for i, row := range records[1:] {
		rowNum := i + 2
		if len(row) < 12 {
			result.Errors++
			errorRows = append(errorRows, ErrorRow{Row: row, Error: "Row has fewer than 12 columns", RowNum: rowNum})
			continue
		}

		partnumber := row[0]
		qty := row[1]
		_ = row[2] // parttype column (unused; reserved)
		make := row[3]
		model := row[4]
		yearfrom := row[5]
		yearto := row[6]
		pos := row[7]
		imgUrl := row[8]
		content := row[9]
		shortContent := row[10]
		fmsi := row[11]

		material := ""
		if len(row) > 12 {
			material = strings.TrimSpace(row[12])
		}

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

		if make == "MISSING" || model == "MISSING" {
			make = "Wagner"
			model = "Universal"
		}

		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 model year: %v", err), RowNum: rowNum})
			continue
		}

		position := imp.parsePosition(pos)

		product := shortContent
		if product == "" || product == "MISSING" {
			product = "Pastilla de Freno"
		}

		tier := ""
		cl := strings.ToLower(content)
		if strings.Contains(cl, "premium") {
			tier = "Premium"
		} else if strings.Contains(cl, "severe") {
			tier = "Heavy Duty"
		}

		quantity, _ := strconv.Atoi(qty)
		if quantity == 0 {
			quantity = 1
		}

		yearFrom := imp.parseYear(yearfrom)
		yearTo := imp.parseYear(yearto)

		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: true},
			Serie:                  pgtype.Text{String: material, Valid: material != "" && material != "MISSING"},
			Tier:                   pgtype.Text{String: tier, Valid: tier != ""},
			Quantity:               pgtype.Int4{Int32: int32(quantity), Valid: true},
			Position:               pgtype.Text{String: position, Valid: position != ""},
			Fmsi:                   pgtype.Text{String: fmsi, Valid: fmsi != "" && fmsi != "MISSING"},
			IncludesHardware:       pgtype.Text{String: "No", Valid: true},
			ImageProduct:           pgtype.Text{String: imgUrl, Valid: imgUrl != "" && imgUrl != "MISSING"},
			VehicleAttrs:           pgtype.Text{String: fmt.Sprintf("%d-%d", yearFrom, yearTo), Valid: true},
			ImageProductDimentions: pgtype.Text{},
			TechnicalSheet:         pgtype.Text{String: content, Valid: content != "" && content != "MISSING"},
			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("  Wagner: %d rows processed\n", i)
		}
	}

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

	return result, nil
}
