package province

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

	"gorm.io/gorm"
)

type ProvinceImportHandler struct {
	UserData domain.User
}

func NewProvinceImportHandler(user_data domain.User) importer.ImportHandler {
	return &ProvinceImportHandler{
		UserData: user_data,
	}
}

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

	if len(row) < 1 {
		errors = append(errors, fmt.Errorf("row is empty"))
		return nil, errors
	}

	name := strings.TrimSpace(row[0])
	if name == "" {
		errors = append(errors, fmt.Errorf("name is required"))
		return nil, errors
	}

	if len(name) < 2 {
		errors = append(errors, fmt.Errorf("name must be at least 2 characters"))
		return nil, errors
	}

	if len(name) > 255 {
		errors = append(errors, fmt.Errorf("name must be at most 255 characters"))
		return nil, errors
	}

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

	return province, nil
}

func (h *ProvinceImportHandler) GetDataString(data importer.RowData) string {
	province := data.(*domain.Province)
	if province.Name != nil {
		return *province.Name
	}
	return ""
}

func (h *ProvinceImportHandler) IsDuplicate(db *gorm.DB, data importer.RowData) bool {
	province := data.(*domain.Province)
	var count int64
	db.Model(&domain.Province{}).Where("UPPER(name) = ?", strings.ToUpper(*province.Name)).Count(&count)
	return count > 0
}

func (h *ProvinceImportHandler) GetTemplateHeaders() []string {
	return []string{"name"}
}

func (h *ProvinceImportHandler) GetTemplateRows() [][]string {
	return [][]string{
		{"DKI Jakarta"},
		{"Jawa Barat"},
		{"Jawa Tengah"},
		{"Jawa Timur"},
	}
}
