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

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

func NewDistrictUsecase(helper helpers.HelperInterface, authUser domain.User) DistrictUsecaseInterface {
	return &DistrictUsecase{Helper: helper, AuthUser: authUser}
}

func (u *DistrictUsecase) GetAll(filter dto.DistrictFilterAllRequest) ([]domain.District, int64, error) {
	var districts []domain.District
	var total int64

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

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

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

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

func (u *DistrictUsecase) Create(name string, provinceID string, cityID string, createdBy string, merchantid *string) (domain.District, error) {
	now := time.Now()

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

func (u *DistrictUsecase) Update(id string, name string, provinceID string, cityID string, updatedBy string) (domain.District, error) {
	var district domain.District
	var oldDistrict domain.District
	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(&district).Error; err != nil {
			return err
		}
		oldDistrict = district
		now := time.Now()
		district.Name = &name
		district.ProvinceID = &provinceID
		district.CityID = &cityID
		district.UpdatedBy = &updatedBy
		district.UpdatedOn = &now
		return tx.Save(&district).Error
	})
	if err != nil {
		return domain.District{}, 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("district", oldDistrict, district, merchantID)
	return district, nil
}

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