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 ModaUsecaseInterface interface {
	GetAll(filter dto.ModaFilterAllRequest) ([]domain.Moda, int64, error)
	GetList(dto.DataTableRequest) (dto.DataTableResponse, error)
	GetByID(id string) (domain.Moda, error)
	Create(name string, createdBy string, merchantid *string) (domain.Moda, error)
	Update(id string, name string, updatedBy string) (domain.Moda, error)
	Delete(id string) error
}

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

func NewModaUsecase(helper helpers.HelperInterface, authUser domain.User) ModaUsecaseInterface {
	return &ModaUsecase{Helper: helper, AuthUser: authUser}
}

func (u *ModaUsecase) GetAll(filter dto.ModaFilterAllRequest) ([]domain.Moda, int64, error) {
	var items []domain.Moda
	var total int64

	db := u.Helper.GetDB("slave")
	tx := db.Model(&items)
	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.Moda{}).Count(&total)
	tx.Order("name ASC")
	if err := tx.Find(&items).Error; err != nil {
		return nil, 0, err
	}
	return items, total, nil
}

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

	response = dt.Render(coldef)
	return response, nil
}

func (u *ModaUsecase) GetByID(id string) (domain.Moda, error) {
	var item domain.Moda
	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(&item).Error; err != nil {
		return domain.Moda{}, err
	}
	return item, nil
}

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

	db := u.Helper.GetDB("master")

	var item domain.Moda
	err := db.Transaction(func(tx *gorm.DB) error {
		item = domain.Moda{
			Name:       &name,
			MerchantID: merchantid,
			CreatedBy:  &createdBy,
			CreatedOn:  &now,
			UpdatedBy:  &createdBy,
			UpdatedOn:  &now,
		}

		return tx.Create(&item).Error
	})
	if err != nil {
		return domain.Moda{}, err
	}
	logUsecase := NewActivityLogUsecase(u.Helper, u.AuthUser)
	logUsecase.LogCreate("moda", item, merchantid)
	return item, nil
}

func (u *ModaUsecase) Update(id string, name string, updatedBy string) (domain.Moda, error) {
	var item domain.Moda
	var oldItem domain.Moda
	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(&item).Error; err != nil {
			return err
		}
		oldItem = item
		now := time.Now()
		item.Name = &name
		item.UpdatedBy = &updatedBy
		item.UpdatedOn = &now
		return tx.Save(&item).Error
	})
	if err != nil {
		return domain.Moda{}, 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("moda", oldItem, item, merchantID)
	return item, nil
}

func (u *ModaUsecase) Delete(id string) error {
	db := u.Helper.GetDB("master")
	return db.Transaction(func(tx *gorm.DB) error {
		var item domain.Moda
		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(&item).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("moda", id, item, merchantID)
		if err := tx.Delete(&domain.Moda{}, "id = ?", id).Error; err != nil {
			return err
		}
		return nil
	})
}
