package usecases

import (
	"cargo-erp-backend/internal/domain"
	"cargo-erp-backend/internal/handlers/dto"
	"cargo-erp-backend/pkg/datatable"
	"cargo-erp-backend/pkg/helpers"
	"fmt"
	"reflect"
	"time"

	"gorm.io/gorm"
)

type ProvinceUsecaseInterface interface {
	GetAll(filter dto.ProvinceFilterAllRequest) ([]domain.Province, int64, error)
	GetList(dto.DataTableRequest) (dto.DataTableResponse, error)
	GetByID(id string) (domain.Province, error)
	Create(name string, createdBy string, merchantid *string) (domain.Province, error)
	Update(id string, name string, updatedBy string) (domain.Province, error)
	Delete(id string) error
}

type ProvinceUsecase struct {
	Helper   helpers.HelperInterface
	AuthUser domain.User
}

func NewProvinceUsecase(helper helpers.HelperInterface, authUser domain.User) ProvinceUsecaseInterface {
	return &ProvinceUsecase{Helper: helper, AuthUser: authUser}
}

func (u *ProvinceUsecase) GetAll(filter dto.ProvinceFilterAllRequest) ([]domain.Province, int64, error) {
	var provinces []domain.Province
	var total int64

	db := u.Helper.GetDB("slave")
	tx := db.Model(&provinces)
	if u.AuthUser.UsersRole_Relation == nil || u.AuthUser.UsersRole_Relation.RoleKey != "SPM" {
		tx = tx.Where(db.Where("merchant_id IS NULL").Or("merchant_id=?", u.AuthUser.MerchantID))
	}
	v := reflect.ValueOf(filter)
	t := reflect.TypeOf(filter)

	for i := 0; i < v.NumField(); i++ {
		if v.Field(i).String() != "" {
			tagKey := t.Field(i).Tag.Get("form")
			tx = tx.Where(fmt.Sprintf("%v=?", tagKey), v.Field(i))
		}
	}
	tx.Model(&domain.Province{}).Count(&total)
	tx.Order("name ASC")
	if err := tx.Find(&provinces).Error; err != nil {
		return nil, 0, err
	}
	return provinces, total, nil
}

func (u *ProvinceUsecase) GetList(req dto.DataTableRequest) (dto.DataTableResponse, error) {

	var response dto.DataTableResponse
	db := u.Helper.GetDB("slave")
	tx := db.Table("province").Joins("LEFT JOIN merchant ON province.merchant_id=merchant.id")
	if u.AuthUser.UsersRole_Relation == nil || u.AuthUser.UsersRole_Relation.RoleKey != "SPM" {
		tx = tx.Where("province.merchant_id IS NULL OR province.merchant_id=?", u.AuthUser.MerchantID)
	}
	dt := datatable.NewDatatable(tx, req)
	coldef := make([]dto.DataTableColDef, 0)
	coldef = append(coldef, dto.DataTableColDef{
		Field:     "province.name",
		Alias:     "name",
		Formatter: nil,
	})
	coldef = append(coldef, dto.DataTableColDef{
		Field:     "merchant.id",
		Alias:     "merchant_id",
		Formatter: nil,
	})
	coldef = append(coldef, dto.DataTableColDef{
		Field:     "province.id",
		Alias:     "id",
		Formatter: nil,
	})

	response = dt.Render(coldef)

	return response, nil
}

func (u *ProvinceUsecase) GetByID(id string) (domain.Province, error) {
	var province domain.Province

	db := u.Helper.GetDB("slave")
	if u.AuthUser.UsersRole_Relation == nil || u.AuthUser.UsersRole_Relation.RoleKey != "SPM" {
		db = db.Where("merchant_id IS NULL OR merchant_id=?", u.AuthUser.MerchantID)
	}

	if err := db.Where("id = ?", id).First(&province).Error; err != nil {
		return domain.Province{}, err
	}

	return province, nil
}

func (u *ProvinceUsecase) Create(name string, createdBy string, merchantid *string) (domain.Province, error) {
	now := time.Now()

	db := u.Helper.GetDB("master")
	var province domain.Province
	err := db.Transaction(func(tx *gorm.DB) error {
		province = domain.Province{
			Name:       &name,
			MerchantID: merchantid,
			CreatedBy:  &createdBy,
			CreatedOn:  &now,
			UpdatedBy:  &createdBy,
			UpdatedOn:  &now,
		}
		return tx.Create(&province).Error
	})
	if err != nil {
		return domain.Province{}, err
	}
	logUsecase := NewActivityLogUsecase(u.Helper, u.AuthUser)
	logUsecase.LogCreate("province", province, merchantid)
	return province, nil
}

func (u *ProvinceUsecase) Update(id string, name string, updatedBy string) (domain.Province, error) {
	var province domain.Province
	var oldProvince domain.Province
	db := u.Helper.GetDB("master")
	err := db.Transaction(func(tx *gorm.DB) error {
		q := tx
		if u.AuthUser.UsersRole_Relation == nil || u.AuthUser.UsersRole_Relation.RoleKey != "SPM" {
			q = tx.Where("merchant_id=?", u.AuthUser.MerchantID)
		}
		if err := q.Where("id = ?", id).First(&province).Error; err != nil {
			return err
		}
		oldProvince = province
		now := time.Now()
		province.Name = &name
		province.UpdatedBy = &updatedBy
		province.UpdatedOn = &now
		return tx.Save(&province).Error
	})
	if err != nil {
		return domain.Province{}, err
	}
	var merchantID *string
	if u.AuthUser.UsersRole_Relation == nil || u.AuthUser.UsersRole_Relation.RoleKey != "SPM" {
		merchantID = u.AuthUser.MerchantID
	}
	logUsecase := NewActivityLogUsecase(u.Helper, u.AuthUser)
	logUsecase.LogUpdate("province", oldProvince, province, merchantID)
	return province, nil
}

func (u *ProvinceUsecase) Delete(id string) error {
	db := u.Helper.GetDB("master")
	return db.Transaction(func(tx *gorm.DB) error {
		var province domain.Province
		q := tx
		if u.AuthUser.UsersRole_Relation == nil || u.AuthUser.UsersRole_Relation.RoleKey != "SPM" {
			q = tx.Where("merchant_id=?", u.AuthUser.MerchantID)
		}
		if err := q.Where("id = ?", id).First(&province).Error; err != nil {
			return err
		}

		var merchantID *string
		if u.AuthUser.UsersRole_Relation == nil || u.AuthUser.UsersRole_Relation.RoleKey != "SPM" {
			merchantID = u.AuthUser.MerchantID
		}
		logUsecase := NewActivityLogUsecase(u.Helper, u.AuthUser)
		logUsecase.LogDelete("province", id, province, merchantID)

		if err := tx.Delete(&domain.Province{}, "id = ?", id).Error; err != nil {
			return err
		}

		return nil
	})
}
