package csvimporter

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

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

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

	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)
	}

	shockBrandID, err := imp.findOrCreateShockBrand(ctx, "Monroe")
	if err != nil {
		return result, fmt.Errorf("failed to get shock brand: %w", err)
	}

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

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

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

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

		if make == "MISSING" || model == "MISSING" {
			result.Errors++
			errorRows = append(errorRows, ErrorRow{Row: row, Error: "Missing make or 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 model year: %v", err), RowNum: rowNum})
			continue
		}

		position := imp.parsePosition(pos)

		product := shortContent
		if product == "" || product == "MISSING" {
			product = "Amortiguador"
		}

		tier := ""
		if strings.Contains(strings.ToLower(content), "oespectrum") {
			tier = "Premium"
		} else if strings.Contains(strings.ToLower(content), "magnum") {
			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.insertShockBrandSpec(ctx, catalogue.CreateShockBrandSpecParams{
			PartNumber:           pgtype.Text{String: partnumber, Valid: true},
			Product:              pgtype.Text{String: product, Valid: true},
			Serie:                pgtype.Text{Valid: false},
			Quantity:             pgtype.Int2{Int16: int16(quantity), Valid: true},
			Tier:                 pgtype.Text{String: tier, Valid: tier != ""},
			Position:             pgtype.Text{String: position, Valid: position != ""},
			ImageProduct:         pgtype.Text{String: imgUrl, Valid: imgUrl != "" && imgUrl != "MISSING"},
			VehicleAttrs:         pgtype.Text{String: fmt.Sprintf("%d-%d", yearFrom, yearTo), Valid: true},
			Notes:                pgtype.Text{String: content, Valid: content != "" && content != "MISSING"},
			FkIdVehicleModelYear: pgtype.Int4{Int32: modelYearID, Valid: true},
			FkIdShockBrand:       pgtype.Int4{Int32: shockBrandID, 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("  Monroe: %d rows processed\n", i)
		}
	}

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

	return result, nil
}
