package subdistrict

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

	"gorm.io/gorm"
)

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

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

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

	if len(row) < 4 {
		errors = append(errors, fmt.Errorf("row must have 4 columns: name, district_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"))
	}

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

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

	provinceName := strings.TrimSpace(row[3])
	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
	}

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

	h.lastProvinceName = provinceName
	h.lastCityName = cityName
	h.lastDistrictName = districtName

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

	return subdistrict, nil
}

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

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

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

func (h *SubdistrictImportHandler) GetTemplateRows() [][]string {
	return [][]string{
		{"Kramat Pulo", "Jakarta Pusat", "Jakarta Pusat", "DKI Jakarta"},
		{"Senen", "Jakarta Pusat", "Jakarta Pusat", "DKI Jakarta"},
		{"Cempaka Putih", "Jakarta Pusat", "Jakarta Pusat", "DKI Jakarta"},
		{"Gambir", "Jakarta Pusat", "Jakarta Pusat", "DKI Jakarta"},
	}
}
