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

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

func NewCityUsecase(helper helpers.HelperInterface, authUser domain.User) CityUsecaseInterface {
	return &CityUsecase{Helper: helper, AuthUser: authUser}
}

func (u *CityUsecase) GetAll(filter dto.CityFilterAllRequest) ([]domain.City, int64, error) {
	var cities []domain.City
	var total int64

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

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

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

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

func (u *CityUsecase) Create(name string, provinceID string, port string, createdBy string, merchantid *string) (domain.City, error) {
	now := time.Now()

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

func (u *CityUsecase) Update(id string, name string, provinceID string, port string, updatedBy string) (domain.City, error) {
	var city domain.City
	var oldCity domain.City
	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(&city).Error; err != nil {
			return err
		}
		oldCity = city
		now := time.Now()
		city.Name = &name
		city.ProvinceID = &provinceID
		city.Port = &port
		city.UpdatedBy = &updatedBy
		city.UpdatedOn = &now
		return tx.Save(&city).Error
	})
	if err != nil {
		return domain.City{}, 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("city", oldCity, city, merchantID)
	return city, nil
}

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