package csvimporter

import (
	"context"
	"fmt"

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

func (imp *Importer) ImportAGLeg(filename string) (ImportResult, error) {
	result := ImportResult{Table: "leg_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)
	}

	legBrandID, err := imp.findOrCreateLegBrand(ctx, "AG")
	if err != nil {
		return result, fmt.Errorf("failed to get leg brand: %w", err)
	}

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

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

		codigo := row[0]
		aplicacion := row[2]
		desde := row[3]
		hasta := row[4]
		pos := row[5]
		imgUrl := row[6]
		producto := row[7]

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

		make := row[1]
		model := aplicacion

		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)

		yearsStr := ""
		yearsRangeStr := ""
		if desde != "" && desde != "MISSING" {
			if hasta != "" && hasta != "MISSING" && hasta != desde {
				yearsRangeStr = fmt.Sprintf("%s-%s", desde, hasta)
			} else {
				yearsStr = desde
			}
		}

		if err := imp.insertLegBrandSpec(ctx, catalogue.CreateLegBrandSpecParams{
			PartNumber:           pgtype.Text{String: codigo, Valid: codigo != ""},
			Product:              pgtype.Text{String: producto, Valid: producto != "" && producto != "MISSING"},
			Serie:                pgtype.Text{Valid: false},
			Quantity:             pgtype.Int2{Int16: 1, Valid: true},
			Tier:                 pgtype.Text{Valid: false},
			Position:             pgtype.Text{String: position, Valid: position != ""},
			Accesories:           pgtype.Text{String: "", Valid: false},
			ImageProduct:         pgtype.Text{String: imgUrl, Valid: imgUrl != "" && imgUrl != "MISSING"},
			VehicleAttrs:         pgtype.Text{String: fmt.Sprintf("%s-%s", desde, hasta), Valid: true},
			TechnicalSheet:       pgtype.Text{String: "", Valid: false},
			FkIdVehicleModelYear: pgtype.Int4{Int32: modelYearID, Valid: true},
			FkIdLegBrand:         pgtype.Int4{Int32: legBrandID, 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%10 == 0 {
			fmt.Printf("  AG Leg: %d rows processed\n", i)
		}
	}

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

	return result, nil
}
