package district

import (
	"cargo-erp-backend/internal/domain"
	"cargo-erp-backend/pkg/helpers"
	"cargo-erp-backend/pkg/importer"
	"fmt"
	"strings"
	"time"

	"gorm.io/gorm"
)

type DistrictImportHandler struct {
	UserData          domain.User
	Helper            helpers.HelperInterface
	lastProvinceName  string
	lastCityName      string
}

func NewDistrictImportHandler(userData domain.User, helper helpers.HelperInterface) importer.ImportHandler {
	return &DistrictImportHandler{
		UserData: userData,
		Helper:   helper,
	}
}

func (h *DistrictImportHandler) ValidateRow(row []string, rowNumber int) (importer.RowData, []error) {
	var errors []error

	if len(row) < 3 {
		errors = append(errors, fmt.Errorf("row must have 3 columns: name, city_name, province_name"))
		return nil, errors
	}

	name := strings.TrimSpace(row[0])
	if name == "" {
		errors = append(errors, fmt.Errorf("name is required"))
	} else if len(name) < 2 {
		errors = append(errors, fmt.Errorf("name must be at least 2 characters"))
	} else if len(name) > 255 {
		errors = append(errors, fmt.Errorf("name must be at most 255 characters"))
	}

	cityName := strings.TrimSpace(row[1])
	if cityName == "" {
		errors = append(errors, fmt.Errorf("city_name is required"))
	}

	provinceName := strings.TrimSpace(row[2])
	if provinceName == "" {
		errors = append(errors, fmt.Errorf("province_name is required"))
	}

	if len(errors) > 0 {
		return nil, errors
	}

	var province domain.Province
	db := h.Helper.GetDB("slave")
	if err := db.Where("UPPER(name) = ?", strings.ToUpper(provinceName)).First(&province).Error; err != nil {
		errors = append(errors, fmt.Errorf("province '%s' not found", provinceName))
		return nil, errors
	}

	var city domain.City
	if err := db.Where("UPPER(name) = ? AND province_id = ?", strings.ToUpper(cityName), province.ID).First(&city).Error; err != nil {
		errors = append(errors, fmt.Errorf("city '%s' not found in province '%s'", cityName, provinceName))
		return nil, errors
	}

	h.lastProvinceName = provinceName
	h.lastCityName = cityName

	now := time.Now()
	district := &domain.District{
		Name:       &name,
		ProvinceID: &province.ID,
		CityID:     &city.ID,
		MerchantID: h.UserData.MerchantID,
		CreatedBy:  &h.UserData.ID,
		CreatedOn:  &now,
		UpdatedBy:  &h.UserData.ID,
		UpdatedOn:  &now,
	}

	return district, nil
}

func (h *DistrictImportHandler) GetDataString(data importer.RowData) string {
	district := data.(*domain.District)
	name := ""
	if district.Name != nil {
		name = *district.Name
	}
	return fmt.Sprintf("%s, %s, %s", name, h.lastCityName, h.lastProvinceName)
}

func (h *DistrictImportHandler) IsDuplicate(db *gorm.DB, data importer.RowData) bool {
	district := data.(*domain.District)
	var count int64
	db.Model(&domain.District{}).
		Joins("JOIN city ON district.city_id = city.id").
		Joins("JOIN province ON district.province_id = province.id").
		Where("UPPER(district.name) = ? AND UPPER(city.name) = ? AND UPPER(province.name) = ?",
			strings.ToUpper(*district.Name), strings.ToUpper(h.lastCityName), strings.ToUpper(h.lastProvinceName)).
		Count(&count)
	return count > 0
}

func (h *DistrictImportHandler) GetTemplateHeaders() []string {
	return []string{"name", "city_name", "province_name"}
}

func (h *DistrictImportHandler) GetTemplateRows() [][]string {
	return [][]string{
		{"Kebayoran Baru", "Jakarta Pusat", "DKI Jakarta"},
		{"Menteng", "Jakarta Pusat", "DKI Jakarta"},
		{"Bandung Wetan", "Bandung", "Jawa Barat"},
		{"Coblong", "Bandung", "Jawa Barat"},
	}
}
