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

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

func NewSubdistrictUsecase(helper helpers.HelperInterface, authUser domain.User) SubdistrictUsecaseInterface {
	return &SubdistrictUsecase{Helper: helper, AuthUser: authUser}
}

func (u *SubdistrictUsecase) GetAll(filter dto.SubdistrictFilterAllRequest) ([]domain.Subdistrict, int64, error) {
	var subdistricts []domain.Subdistrict
	var total int64

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

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

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

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

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

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

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

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